私は、整数をチェックし、ユーザが17以上の整数を正しく入力するまでループを維持する関数を作成しようとしています。しかし、「K」や「&」のような誤った入力をすると、無限ループに陥るでしょう。正しい入力を得るためにtryとcatchでループを維持するには?
public static int getAge(Scanner scanner) {
int age;
boolean repeat = true;
while (repeat) {
try
{
System.out.println("Enter the soldier's age: ");
age = scanner.nextInt();
repeat = false;
}
catch(InputMismatchException exception)
{
System.out.println("ERROR: You must enter an age of 17 or higher");
repeat = true;
}
}
return age;
}
[正しくなく、ユーザが応答するまで、whileループでみてくださいキャッチを使用しようとする可能性のある重複無効なデータを入力する(Java)](https://stackoverflow.com/questions/27208796/trying-to-use-try-catch-in-a-while-loop-until-the-user-answers-correctly-without) – vinS
あなたのソリューションの問題は何ですか?それは機能しません。質問をするのを忘れました。 –