4

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?

4

2 回答 2

6
keyboard.hasNextInt()

阻塞,直到它有输入要检查。当它这样做时,true如果它找到一个整数值,则返回,否则返回 false。

因此,如果您输入一个整数值,while则永远不会进入循环。如果你不这样做,keyboard.next()循环内部会清除你输入的值,让你再试一次。

于 2013-10-23T21:41:46.753 回答
0

只要您不输入有效的整数值,Scanner.hasNextInt() 就不会返回 true。由于在 while 条件下检查 hasNextInt() 的否定 - 它打印“确保输入一个整数”。直到输入整数值。

希望这有助于 Scanner.hasNextInt()

于 2013-10-23T21:43:15.007 回答