Why does the program not get input from the user?

Evan Zhao :

I am new to Java and I am trying to make a guessing game. In one line of my code, I try to get input from the user. However, it seems like the program did not run that line of code. Why did that happen? The problem occurred in my main method:

Scanner input = new Scanner(System.in);

System.out.println("Let's play a guessing game!");
while (true){
    // get a random number from 1 to 10
    int random = (int) (Math.random() * 10) + 1;
    System.out.println("I am thinking of a number between 1 and 10.");
    System.out.print("What do you think it is? ");
    int guess = input.nextInt();
    System.out.println((guess == random) ? "You are correct!":"You're wrong! The number was " + random);
    System.out.print("Play again? (Y/N)");

    // this line is where the problem occurred.
    String play = input.nextLine();
    if (play.equalsIgnoreCase("N"))
        break;
}

After guessing a number, the program just ignored the line where it asked the user if they want to play again. Why is that happening?

Javier Silva Ortíz :

The Scanner.nextInt method does not read the newline character when you press the "Enter" key, hence Scanner.nextLine returns right after reading that newline.

The same thing happens when you use Scanner.nextLine after any Scanner.next* except for nextLine itself. To solve it, you can call Scanner.nextLine after each Scanner.nextInt to consume the pending newline.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=357026&siteId=1