3

Here is the skeleton of some basic code I am writing to make a simple game:

    Scanner in = new Scanner(System.in);

    String name;
    String playing;
    int age;

    do {

        System.out.println("Enter your name");
        name = in.nextLine();

        System.out.println("Enter your age");
        age = in.nextInt();

        System.out.println("Play again?");
        playing = in.nextLine();

    } while (true);

The code does not work as expected, for example, here is the expected functioning of the code:

Enter your name
John
Enter your age
20
Play again?
Yes
Enter your name
Bill
...

However, there is an issue with reading the Play again line, this is the actual output:

Enter your name
John
Enter your age
20
Play again?
Enter your name

As you can see "Enter your name" is being displayed again before "Play again?" is able to accept input. When debugging the playing variable is set to "", so there is no input that I can see and I cannot figure out what is being consumed. Any help would be appreciated, thanks!

Mat
  • 202,337
  • 40
  • 393
  • 406
Mike
  • 133
  • 1
  • 4

4 Answers4

5

nextInt() doesn't consume the end-of-line, even if the int is the only thing in there.

Add another nextLine() after reading the int, and either discard its value completely, or check that it is empty if you want to prevent people from entering anything but an int.

Mat
  • 202,337
  • 40
  • 393
  • 406
3

The problem is that after calling nextInt() there is still a '\n' in the buffer and so that is what is passed. use in.next() instead of in.nextLine().

  • 1
    Using `next` is a bad idea. What happens if someone enters `a b c` as a name? – Mat May 06 '12 at 06:12
0

Use next() method in Scanner class instead of nextLine() method.

    Scanner in = new Scanner(System.in);

    String name;
    String playing;
    int age;

    do {

        System.out.println("Enter your name");
        name = in.next();

        System.out.println("Enter your age");
        age = in.nextInt();

        System.out.println("Play again?");
        playing = in.next();

    } while (true);

for more information refer Java Documentation for Scanner class Output :

Enter your name
Kanishka
Enter your age
23
Play again?
Yes
Enter your name
....
Kanishka Dilshan
  • 724
  • 2
  • 10
  • 19
0

You should use the following code for the next line reading.

Scanner scanner = new Scanner(System.in).useDelimiter("\n");

And for reading the line you should write

scanner.next();
Bhavik Ambani
  • 6,557
  • 14
  • 55
  • 86