2016-05-13 399 views
0

我有這個try/catch包裹在do/while循環中,因爲在try/catch引發錯誤消息之後,我想讓它循環回到頂部。我嘗試過/同時,而且,我試着將代碼中的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語句放在循環之外。

0

你可以給3個選項 - 一個選項退出

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

內部while循環,你可以添加

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); 
     } 

} 

,或者你想避免嘗試趕上:

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();是必要的 –