我正在使用以下代码:
while (invalidInput)
{
// ask the user to specify a number to update the times by
System.out.print("Specify an integer between 0 and 5: ");
if (in.hasNextInt())
{
// get the update value
updateValue = in.nextInt();
// check to see if it was within range
if (updateValue >= 0 && updateValue <= 5)
{
invalidInput = false;
}
else
{
System.out.println("You have not entered a number between 0 and 5. Try again.");
}
} else
{
System.out.println("You have entered an invalid input. Try again.");
}
}
但是,如果我输入“w”,它会告诉我“您输入了无效的输入。再试一次。” 然后它将进入一个无限循环,显示文本“指定 0 到 5 之间的整数:您输入的输入无效。再试一次。”
为什么会这样?程序是否应该等待用户输入并在每次到达语句时按回车:
if (in.hasNextInt())