whileループで選択メニューを作成しました。ユーザーが有効な選択をするためには、メニューをtry catchブロックに入れてください:選択メニューについての試行錯誤
例外がキャッチされたらユーザーに新しいチャンスを与えてもらいたいので、try-catchブロックをwhile(true)ループです。しかし、このようなループを使用すると、アクションがコード化されている部分が到達不能なコードになります。
これを行う方法はありますか?
さらに、ユーザーが存在しない選択肢オプションを入力しないようにするにはどうすればよいですか?
while (choice != 0) {
/* Ask for player's choice */
while(true) {
try
{
BufferedReader menuInput = new BufferedReader(new InputStreamReader(System.in));
System.out.println();
System.out.println("Please choose between the following options:'");
System.out.println(" (1) Make new animal");
System.out.println(" (2) Feed Animals");
System.out.println(" (3) Count animals");
System.out.println(" (0) Quit");
System.out.print("Enter your choice: ");;
choice = Integer.parseInt(menuInput.readLine());
} catch (NumberFormatException ex) {
System.err.println("Not a valid number");
} catch (IOException e) {
System.out.println("Failed to get input");
}
}
// first choice option:
if (choice == 1) {
//actions
}
// second choice option:
if (choice == 2) {
//actions
}
// third choice option:
if (choice == 3) {
//actions
}
}
System.out.print("Thank you for playing!")
*ループを壊す*状態があるはずです。たとえば、 'break;'ステートメントです。 – David
現在の選択を処理する前に入力を検証する特別なプライベートメソッドを記述することができます。 – pidabrow