【发布时间】:2013-10-23 21:39:33
【问题描述】:
为什么会这样:
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 时偶然发现了这一点,我不知道它为什么会起作用,或者我是否遗漏了一些可怕的错误。它似乎工作得很好,这很好,但我不明白为什么“确保你输入一个整数”文本并不总是显示。谁能解释一下?
【问题讨论】:
标签: java while-loop