我正在尝试创建一个代码,其中应该输入一个int,然后如果int不在9到99之间则有异常,如果输入double而不是int则是另一个异常,然后是第三个异常输入字符串。我该怎么做呢?我有到目前为止我所拥有的,但我不知道如何纠正它。感谢
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);
}
答案 0 :(得分:1)
方法 .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();
}