ニールB:
無限に繰り返すことから、このwhileループを停止する方法を見つけ出すことはできません。私が使用しているhasNextInt
ユーザーの入力がintであるかどうかをチェックします。int型は無限ループ反復を入力しない場合。
public static void validatingInput(){
Scanner scan = new Scanner(System.in);
boolean valid = false;
int userNumber = 0;
while(!valid) {
System.out.println("Enter number between 1 and 20: ");
if (scan.hasNextInt()) {
userNumber = scan.nextInt();
valid = true;
} else
System.out.print("Not an int. ");
}
}
Mureinik:
あなたはそれが次のトークンを読み取ることができるようにするために、スキャナからのトークンを消費する必要があります。
while (!valid) {
System.out.println("Enter number between 1 and 20: ");
if (scan.hasNextInt()) {
userNumber = scan.nextInt();
valid = true;
} else
System.out.print("Not an int. ");
scan.next(); // Skip a token
}
}