次のコードを使用しています。
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())