2016-12-26 4 views
0

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!") 
+2

*ループを壊す*状態があるはずです。たとえば、 'break;'ステートメントです。 – David

+0

現在の選択を処理する前に入力を検証する特別なプライベートメソッドを記述することができます。 – pidabrow

答えて

2

それを行うのは非常に最も簡単な方法は、あなたのループ上のブールフラグを設定することです:

boolean waitingForAnswer = true; 

してからちょうどwhile(waitingForAnswer)にごwhileループ条件を変更し、1がされた後falsewaitingForAnswerを設定受け入れられた。

これで、同じ構造を使用して、5などの入力を防ぐことができます。ちなみに 、下部にif文のあなたの文字列がひどくないです:単に値が認められたものですかどうかをチェックされていない場合は、waitingForAnswer

EDITを変更しない、ということが最後にifにタグを付けます効率的。ユーザが「1」を入力すると、if (choice==1)ブロックがトリガされ、次に、それが2であるかどうか、それが3に等しいかどうかなどを確認するために進みます。そこにelse ifを使用してください。

もう1つのEDIT: また、入力ストリームリーダーをループ外に作成します。現在、ループが実行されるたびに新しいものを作成しています。

関連する問題