2016-05-13 4 views
0

try/catchの後にエラーメッセージがスローされたため、このtry/catchをdo/whileループの周りにラップしています。私はdo/whileを試してみましたが、whileループをコード内の別の場所に配置しようとしましたが、何も動作しませんでした。例外がスローされ、無限ループに入るまで、プログラムは正常に動作します。エラーメッセージが表示されたら、上にループバックします。Javaでループが無期限にループしないようにするにはどうすればよいですか?

public static void main(String[] args) { 

    Scanner input = new Scanner(System.in); 

    Integer userInput; 
    do { 
    try{ 
    System.out.print("Enter a number? \n"); 
    userInput = input.nextInt(); 

     if (userInput == 1) 
     Animal1.displayMessage();//Display the total 
     if(userInput == 2) 
     Animal2.displayMessage();//Display the total 

     } 
     catch (Exception e) { 
     System.out.println(" That's not right "); 
     break; 

     } 
     } while (true); 
     } 

}

これは、エラーメッセージを表示した後に何をするかです。

Enter a number? 
That's not right 
Enter a number? 
That's not right 
Enter a number? 
That's not right 
Enter a number? 
That's not right 
Enter a number? 
That's not right 
Enter a number? 
That's not right 
Enter a number? 
That's not right 
Enter a number? 
That's not right 
Enter a number? 
Enter a number? 

私がそれを止めなければ、それはただ続けるだけです。

+0

私は多くの不確定ループを持っています。私は本当にそれらをより確実にするために働くべきです。 – markspace

+2

これは私の説明どおり正しく動作します。 –

+0

私はちょうどあなたのコードをテストしました。私は数字を入力すると無限にループしますが、他の入力があればループを終了します。 –

答えて

-1

try/catchステートメントをループの外側に配置する必要があります。あなたは3つのオプションを与えることができ

0

- whileループの内側

System.out.print("Enter a number? \n 1 to display Animal1 total\n2 to display Animal2 total\n 3 to exit"); 

を終了する一つのオプションは、あなたが

if (userInput == 3) break; 
1

を追加することができますが、この回避策を試すことができます。

public static void main(String[] args) { 

    Scanner input = new Scanner(System.in); 

    Integer userInput; 
    do { 
    try{ 
    System.out.print("Enter a number? \n"); 
    userInput = input.nextInt(); 

     if (userInput == 1) 
     Animal1.displayMessage();//Display the total 
     if(userInput == 2) 
     Animal2.displayMessage();//Display the total 

     } 
     catch (Exception e) { 
     System.out.println(" That's not right "); 
     input.next(); 

     } 
     } while (true); 
     } 

} 

場合や、 try-catchを避けたい:

public static void main(String[] args) { 

     Scanner input = new Scanner(System.in); 

     Integer userInput = 0; 
     do { 
      System.out.print("Enter a number? \n"); 
      if (input.hasNextInt()) 
       userInput = input.nextInt(); 
      else { 
       System.out.println(" That's not right "); 
       input.next(); 
      } 
      if (userInput == 1) 
       Animal1.displayMessage();//Display the total 
      ;// Display the total 
      if (userInput == 2) 
       Animal2.displayMessage();//Display the total 

     } while (true); 
    } 
+0

はい、input.next();必要です –

関連する問題