Simple Java Scanner Code Doesn't Work

Here is the skeleton of some basic code that 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 a problem 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 see, "Enter your name" is displayed again until "Play again"? can accept input. When the debugging of the game variable is set to "", so there is no input that I can see, and I can not understand what is being consumed. Any help would be appreciated, thanks!

+3
source share
4 answers

nextInt()does not consume the end of the line, even if int- the only thing that is.

nextLine() int , , , , , int.

+5

, nextInt() "\n", , . in.next() in.nextLine().

+3

next() Scanner nextLine().

    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);

. Java- :

Enter your name
Kanishka
Enter your age
23
Play again?
Yes
Enter your name
....
0

.

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

scanner.next();
0

All Articles