Why does this loop work?

Why does it work:

Scanner keyboard = new Scanner(System.in);
int i;
int beerBottles = 100;

//Asks the user for the number of beer bottles on the wall
System.out.println("How many bottles of beer are on the wall?");

while (!keyboard.hasNextInt())
{
System.out.println("Make sure you enter an integer.");
keyboard.next();
}
//Sets beerBottles to the user entered value
beerBottles = keyboard.nextInt();

I stumbled upon this, trying to make sure that user input was an integer without using try / catch, and I have no idea why it works or something is terribly wrong that I went missing. It seems to work fine, which would be great, but I don’t understand why the text “Make sure you enter an integer” is not always displayed. Can anyone explain?

+4
source share
2 answers
keyboard.hasNextInt()

blocks until an input for verification is entered. When he does this, he returns trueif he finds an integer value, and false otherwise.

, , while . , keyboard.next() , .

+6

, Scanner.hasNextInt() true. hasNextInt() while, ", ". Integer.

, Scanner.hasNextInt()

0

All Articles