我已經寫了非常簡單的代碼(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);
}
}
當處理異常,你應該清除'Scanner'對象。 –
謝謝barak。 「清除掃描儀對象」是什麼意思? –
我的意思是,重置此對象。請參閱上面我指出的問題的答案(或下面的兩個答案,它們給出與其他問題的答案相同的解決方案)。 –