为什么这个while循环工作?

时间:2013-10-23 21:39:34

标签: 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();

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

2 个答案:

答案 0 :(得分:6)

keyboard.hasNextInt()

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

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

答案 1 :(得分:0)

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

希望这会有所帮助 Scanner.hasNextInt()