为什么这个while循环工作?

use*_*241 4 java while-loop

为什么这样做:

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();
Run Code Online (Sandbox Code Playgroud)

我偶然发现这一点,同时试图确保用户输入是一个整数而不使用try/catch,我不知道它为什么会起作用,或者如果我错过了一些可怕的错误.它似乎工作得很好,这将是伟大的,但我不明白为什么"确保你输入一个整数"文本并不总是显示.谁能解释一下?

Kep*_*pil 6

keyboard.hasNextInt()
Run Code Online (Sandbox Code Playgroud)

阻止,直到它有输入来检查.如果是,true则在找到整数值时返回,否则返回false.

因此,如果输入整数值,while则永远不会输入循环.如果没有,keyboard.next()循环内部会清除您输入的值,让您再试一次.