user2913241
user2913241

Reputation: 65

Why does this while loop work?

Why does this 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 on this while trying to make sure that the user input was an integer without using try/catch and I have no idea why it works or if something is horrendously wrong that I'm missing. It seems to work perfectly, which would be great, but I don't understand why the "Make sure you enter an integer" text doesn't always show. Can anyone explain?

Upvotes: 5

Views: 192

Answers (2)

Reji
Reji

Reputation: 3516

As long as you don't enter a valid integer value, the Scanner.hasNextInt() does not return a true. Since the negation of hasNextInt() is being checked at the while condition - it prints "Make sure you enter an integer." until an Integer value is entered.

Hope this helps Scanner.hasNextInt()

Upvotes: 1

Keppil
Keppil

Reputation: 46209

keyboard.hasNextInt()

blocks until it has input to examine. When it does, it returns true if it finds an integer value, and false otherwise.

Therefore, if you enter an integer value, the while loop is never entered. If you didn't, the keyboard.next() inside the loop clears the value you entered to let you try again.

Upvotes: 7

Related Questions