2013-09-26 100 views
2

我正在做一個計算階乘的程序,我寫了一個循環來捕獲NumberFormatException和InputMismatchException。 NumberFormatException運行良好並循環回到try塊,但InputMismatchException一遍又一遍地顯示其消息,而沒有循環返回到try塊。我不確定我做錯了什麼。這裏是我的代碼:爲什麼我的catch塊永遠循環?

import java.util.*; 

public class Factorial 
{ 
public static void main(String[] args) 
{ 
    Scanner s = new Scanner(System.in); 
    System.out.println("Factorial Test Program\n"); 

    boolean success = false; 

    while (!success) 
    { 
     try 
     { 
      System.out.print("Enter an integer number: "); 
      int number = s.nextInt(); 

      if (number < 0) throw new NumberFormatException(); 

      long f = number; 

      for (int i = number-1; i>0; i--) 
       f *= i; 

      if (number==0) f=1; 

      System.out.printf("The factorial of %s is %s.\n", number, f); 
      success=true; 

      System.out.println("Done!"); 
     } 
     catch (NumberFormatException e) 
     { 
      System.out.println("Factorial of this value cannot be represented as an integer"); 
     } 
     catch (InputMismatchException e) 
     { 
      System.out.println("You must enter an integer - please re-enter:"); 
     } 
    } 
} 
} 
+2

不是你catch塊循環永遠但while循環... –

+2

因爲你永遠都不會成功。 –

+0

不是整個塊循環時,它只是InputMismatchException塊的內容永遠循環。如果它循環回到while循環的開始,那就沒問題了。 – user1923768

回答

6

一旦無效的整數輸入s.nextInt()汽車無通過while環換行符和重複這個過程循環往復。另一方面,當發生NumberFormatException時,一個有效整數已經被讀取,所以沒有換行符被傳遞到while循環。

InputMismatchException範圍內添加s.nextLine()異常塊會解決此問題。

+0

爲什麼一個異常工作正常,而另一個循環永遠循環? – user1923768

+0

當NumberFormatException發生時,您已經成功讀取了一個整數,所以沒有換行符被傳遞給while循環 – Reimeus

+0

好吧,因此s.nextInt()在異常上失敗,因此輸入緩衝區不變?因此,在我有機會輸入任何內容之前,它基本上會自動輸入無效數據?不過,我仍然可以看到「輸入整數:」嗎?我不。這只是「你必須輸入一個整數 - 請重新輸入:」一遍又一遍。 – user1923768

0

add catch break; in catch block。 或使try塊內while循環

try { 

    while() { 

    } 

} catch() { 

}