2015-04-23 74 views
1

我已經寫了非常簡單的代碼(n1/n2 = sum),同時嘗試學習try/catch異常處理。代碼不會退出while循環(試圖捕獲異常)

我有一個do/while循環,當成功運行時應該使x = 2。如果不是,x = 1,用戶輸入可以再次輸入。

代碼編譯並運行,但如果我嘗試,例如n1 = 10,n2 = stackoverflow,捕獲異常的prinln會永遠運行!

爲什麼迴路卡住了?

在此先感謝

import java.util.*; 

public class ExceptionHandlingMain { 
    public static void main(String[] args) { 

     Scanner input = new Scanner(System.in); 

     int x = 1; // x originally set to 1 
     do { // start of do loop 
      try { 
       System.out.println("Enter numerator: "); 
       int n1 = input.nextInt(); 

       System.out.println("Enter divisor"); 
       int n2 = input.nextInt(); 

       int sum = n1/n2; 

       System.out.println(n1 + " divided by " + n2 + " = " + sum); 
       x = 2; 
// when the code is completed successfully, x = 2 and do/while loop exits 

      } catch (Exception e) { 
       System.out.println("You made a mistake, moron!"); 
      } 
     } while (x == 1); 
    } 
} 
+2

當處理異常,你應該清除'Scanner'對象。 –

+0

謝謝barak。 「清除掃描儀對象」是什麼意思? –

+0

我的意思是,重置此對象。請參閱上面我指出的問題的答案(或下面的兩個答案,它們給出與其他問題的答案相同的解決方案)。 –

回答

2

在您的catch塊中添加input.nextLine()以清除讀取的行。

1

那是因爲你是按號碼輸入回車鍵後。

我建議你添加input.nextLine();調用,所以你在從Scanner讀取你的輸入後也要使用返回鍵。

因此,與nextInt API,當你鍵入比如:

123<return key> 

nextInt將剛剛拿起123爲一個字符串,將其轉換成一個數字,離開返回鍵一部分是。

+0

解決方案是正確的,但你的解釋是錯誤的。當用戶輸入'numerator'或'divisor''stackoverflow + ENTER'時,'Iinput.nextInt()'拋出一個'InputMismatchException'並且將'stackoverflow'作爲下一個輸入值。由於輸入在catch塊中沒有被移除,所以它停留在那裏,下一個'Iinput.nextInt()'將再次拋出'InputMismatchException'並且離開....等等。 ;-) – SubOptimal

0

謝謝@barak馬諾斯(和其他人誰回答)

加入後

input.nextLine(); 

立即

System.out.println("You made a mistake, moron!"); 

清除輸入流,並允許用戶輸入新數據。

舉:改編自 回答https://stackoverflow.com/a/24414457/4440127 用戶:user3580294