2014-11-17 68 views
0

後,我想拋出一個異常,這是我的代碼調用主闖闖拋出異常

System.out.println("please enter an intger to compute its factorial:"); 
    BufferedReader bufferedreader = new BufferedReader(new InputStreamReader(System.in)); 
    String number =""; 
    try { 
     try { 
      number = bufferedreader.readLine(); 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 

     } 

    intN=Integer.parseInt(number); 
     if (intN > 0) {   // from the command line 
      FactorialIter f = 
       new FactorialIter(Math.abs(intN)); 

     } 
    } catch (NumberFormatException e) { 
     // TODO Auto-generated catch block 
     System.out.println("error you should enter a number"); 
     throw new MyExceptions("try again please use integer numbers"); 
     //if possible to restart the main 

    } 

所以當以往用戶輸入一個字符,程序將拋出一個異常,然後重新啓動後重新啓動程序這可能嗎??

+0

嘗試檢查了這個問題: http://stackoverflow.com/questions/4159802/how-can-i-restart-a-java-application – DrRoach

回答

2

通常,不應該遞歸調用main,特別是爲了重新啓動程序。

如果您想回到程序中的某個位置,請使用循環。這裏是你如何能做到這一個例子:

boolean done = false; 
do { 
    done = true; 
    try { 
     ... 
    } catch (NumberFormatException e) { 
     System.out.println("error you should enter a number"); 
     done = false; 
    } 
} while (!done); 

循環將每個異常處理程序設置donefalse時間繼續從頭開始。

0

你可以把它放在一個循環中。

While(isValid != TRUE) 
{ 
     try 
     { 
      try { 
       number = bufferedreader.readLine(); 
      } catch (IOException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 

      intN=Integer.parseInt(number); 
      if (intN > 0) {   // from the command line 
        FactorialIter f = 
         new FactorialIter(Math.abs(intN)); 
       isValid = TRUE; 

      } 

     } 
     catch (NumberFormatException e) 
     { 
      System.out.println("error you should enter a number"); 
      System.out.println("try again please use integer numbers"); 
      isValid = FALSE; 
     } 

}