【发布时间】:2018-11-14 01:07:10
【问题描述】:
我不确定为什么当我输入除整数值以外的任何内容时,输出未显示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;
}
这是我想要得到的输出:
【问题讨论】:
标签: java exception error-handling exception-handling try-catch