int choice = 0;
while ((choice != 1) || (choice !=2)){
System.out.println("1. Option 1");
System.out.println("2. Option 2");
try{
choice = scanner.nextInt();
}
catch(InputMismatchException e){
System.out.println(e);
}
if (choice == 1){
System.out.println("Option 1");
break;
}
if (choice == 2){
System.out.println("Option 2");
break;
}
System.out.println("Please enter a valid choice.");
}
非intが入力された場合を処理しようとしています。なぜこれが無限ループに陥るのでしょうか? try catchブロックを追加しようとするとうまくいきました。無限ループを引き起こすJavaエラー処理
であなたのtryキャッチを置き換えるしかし、その後のプログラムは、あなたが別の値で入力することができますので、私は戻ってループにそれをしたい、終了。 – unskilledidiot
改行トークンを使用する必要があります。 http://stackoverflow.com/questions/13102045/skipping-nextline-after-using-next-nextint-or-other-nextfoo-methodsを参照してください。 –