我正在尝试创建一个代码,其中应该输入 int,然后如果 int 不在 9 到 99 之间则有异常,如果输入 double 而不是 int,则有另一个异常,如果输入了 double 则有第三个异常输入字符串。我该怎么做呢?我到目前为止所拥有的内容如下,但不知道如何纠正它。谢谢
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean correct = true;
do {
try {
System.out.println("Enter an Integer between 9 and 99");
int number = input.nextInt();
if (number >= 9 && number <= 99) {
System.out.println("Thank you, Initialization completed");
correct = false;
} else if (number < 9 || number > 99) {
throw new Exception("Integer is not within the range");
}
if (input.hasNextDouble()) {
throw new Exception("Integer not entered");
} else {
correct = false;
}
if (input.hasNext("")) {
throw new NumberFormatException("Integer not entered");
} else {
correct = false;
}
} // check for range
catch (Exception e1) {
System.out.println("Number is not within 9 and 99");
System.out.println();
input.nextLine();
} catch (Exception e2) {
System.out.println("An integer was not entered");
System.out.println();
input.nextLine();
} catch (NumberFormatException e3) {
System.out.println("An integer was not entered");
System.out.println();
input.nextLine();
}
} while (correct);
}
最佳答案
方法.getMessage()返回构造函数中给出的字符串:
throw new Exception("HERE");
当您捕获 Exception 时,您还会捕获 NumberFormatException、InputMismatchException 等。 所以你必须最后捕获更广泛的。
catch (NumberFormatException e3) { // Precisier goes first
System.out.println("An integer was not entered");
System.out.println();
input.nextLine();
}
catch (Exception e1) {
System.out.println(e1.getMessage());
System.out.println();
input.nextLine();
}
关于java - int 的三个异常(exception),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22896308/