1
我試圖在while循環內執行try catch塊。當我要求用戶輸入一個數字(應該是一個double)時,我使用try catch來捕獲任何輸入不匹配的異常。我在while循環中嵌套了這個,這樣如果有任何異常被捕獲,用戶可以根據需要重新輸入它們的輸入。問題是,如果發現異常,掃描器將不允許用戶因某種原因重新輸入輸入。當您返回到小時= kb.nextDouble的行時,錯誤在第二次迭代期間被捕獲。這是代碼。在while循環中執行try/catch
boolean condition = true;
while(condition==true) {
try {
// prompt user to enter hours of service used
System.out.println("Please enter the number of hours of service you have used: ");
hours = kb.nextDouble();
// validate hours
while(hours <=0){
System.out.println("You must enter a positive number.");
hours = kb.nextDouble();
} condition = false;
} catch (InputMismatchException ime){
System.out.println("You must enter a decimal value for hours.");
}
}
感謝您的解釋! – 2015-08-05 22:13:13