Java: Infinite loop using Scanner in.hasNextInt()
2022-09-02 03:03:37
我使用以下代码:
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 之间的整数:您输入了无效的输入。请重试。
为什么会发生这种情况?程序不是应该等待用户在每次到达语句时输入并按 Enter 键吗:
if (in.hasNextInt())