[英]Try-Catch Exception Handling does not provide the correct response
我不確定為什么當我輸入除整數以外的任何內容時,輸出沒有顯示Invalid Format!
。
這是我要實現的異常處理。 另外,如何在finally
子句中關閉Scanner
而又不會導致無限循環。
class ConsoleInput {
public static int getValidatedInteger(int i, int j) {
Scanner scr = new Scanner(System.in);
int numInt = 0;
while (numInt < i || numInt > j) {
try {
System.out.print("Please input an integer between 4 and 19 inclusive: ");
numInt = scr.nextInt();
if (numInt < i || numInt > j) {
throw new Exception("Invalid Range!");
} else {
throw new InputMismatchException("Invalid Format!");
}
} catch (Exception ex) {
System.out.println(ex.getMessage());
scr.next();
}
}
scr.close();
return numInt;
}
這是我想要獲得的輸出:
如果您輸入的不是int,則錯誤將拋出該行:
numInt = scr.nextInt();
然后陷入catch塊,從而跳過打印語句。 您需要檢查是否存在下一個int:
if(!scr.hasNextInt()) {
throw new InputMismatchException("Invalid Format!");
}
另外,如何在finally子句中關閉掃描器而又不會導致無限循環。
您無需在finally塊中關閉Scanner
。 實際上,您根本不應該關閉它。 關閉System.in
是不好的做法。 通常,如果您沒有打開資源,則不應關閉它。
您需要在Exception catch塊之前的另一個catch塊中捕獲InputMismatchException,並添加scr.next();。 如下所示:
public static int getValidatedInteger(int i, int j) {
Scanner scr = new Scanner(System.in);
int numInt = 0;
while (numInt < i || numInt > j) {
try {
System.out.print("Please input an integer between 4 and 19 inclusive: ");
numInt = scr.nextInt();
if (numInt < i || numInt > j) {
throw new Exception("Invalid Range!");
}
} catch (InputMismatchException ex) {
System.out.println("Invalid Format!");
scr.next();
} catch (Exception ex) {
System.out.println(ex.getMessage());
scr.next();
}
}
scr.close();
return numInt;
}
下面的代碼將為您工作,這是您可以用來獲取期望輸出的另一種方法。 在這段代碼中,我已經在catch代碼塊中處理了InputMismatch。
public static int getValidatedInteger(int i, int j) {
Scanner scr = new Scanner(System.in);
int numInt = 0;
while (numInt < i || numInt > j) {
try {
System.out.print("Please input an integer between 4 and 19 inclusive: ");
numInt = scr.nextInt();
if (numInt < i || numInt > j) {
System.out.println("Incorrect Range!");
}
} catch (InputMismatchException ex) {
System.out.println("Incorrect format!");
scr.next();
}
}
scr.close();
return numInt;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.