0

I was writing my first, well second if you count hello world, program and ran into a small issue.

My code:

import java.util.*;

class test {
public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);

    System.out.print("What is your name: ");
    String name = scan.nextLine();

    System.out.print("What is your favorite number: ");
    int favoriteNumber = scan.nextInt();

    System.out.print("What is your favorite game: ");
    String game = scan.nextLine();
}
}

So it scans in name and favoriteNumber but the program ends before asking the user to enter a favorite game. Essentially the user can only enter text twice instead of three times like I would like.

Cœur
  • 32,421
  • 21
  • 173
  • 232
user2545067
  • 15
  • 1
  • 3

2 Answers2

1

Just a guess: scan.nextInt() does not consume the trailing newline character after the user presses enter. The subsequent call to scan.nextLine() then finds a newline character waiting.

Try switching out int favoriteNumber = scan.nextInt(); for String favoriteNumber = scan.nextLine(); to see if that fixes the issue. If it does, my hypothesis is correct.

If that is the case, then you should probably use Integer.parseInt to convert this string into an integer. The problem here is effectively that you really want to collect 3 lines of input, where a line is defined as "any sequence of characters ending with a newline". Your program is currently written to request a line, an int, then a line, rather than "3 lines of input, one of which contains an int".

Gian
  • 13,057
  • 39
  • 50
  • +1 Other way is to invoke `scan.nextLine()` right after `nextInt();` to consume remaining new line mark (this way is not so clear as `int favoriteNumber = Integer.parseInt(scan.nextLine())` but is good to confirm root of the problem). – Pshemo Jul 03 '13 at 05:12
  • True, that might be a nice simple solution. – Gian Jul 03 '13 at 05:15
0

an exception must be thrown in here scan.nextInt(); Check whether you entered a proper int

Sanjaya Liyanage
  • 4,366
  • 9
  • 33
  • 50