gpt4 book ai didi

java - 如何创建检查 int 范围、数字类型而不是 char 的异常?

转载 作者:行者123 更新时间:2023-11-30 04:27:36 24 4
gpt4 key购买 nike

我正在尝试解决异常问题,但我遇到的问题是我需要创建一个程序,要求用户输入数字 9-99。必须使用 3 种不同的异常对该数字进行错误检查。

e1: number is outside of the range (200)

e2: number is of a data type other than integer (double)

e3: input is another data type other than number (char)

我尝试在 if 结构中创建模式以使所有三个都起作用,但是我无法让它区分 e2 和 e3。它将始终默认为 e2。这就是我所拥有的,只有两个异常(exception),但我非常感谢您帮助我弄清楚如何实现第三个异常(exception)。谢谢。

public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean tryAgain = true;
do {
try {
System.out.println("Please enter an integer between 9 and 99: ");

int inInt = input.nextInt();

if (inInt >= 9 && inInt <= 99){
System.out.println("Thank you. Initialization completed.");
tryAgain = false;
}
else if (inInt < 9 || inInt > 99){
throw new NumberFormatException("Integer is out of range.");
}
}
catch (NumberFormatException e1) { // Range check
System.out.println("* The number you entered is not between 9 and 99. Try again.");
System.out.println();
input.nextLine();
}
catch (InputMismatchException e2) { // Something other than a number
System.out.println("* You did not enter an integer. Try again.");
System.out.println();
input.nextLine();
}
} while(tryAgain);
}

}

这是我现在得到的输出:

Please enter an integer between 9 and 99: 2

  • The number you entered is not between 9 and 99. Try again.

Please enter an integer between 9 and 99: f

  • You did not enter an integer. Try again.

Please enter an integer between 9 and 99: 88

Thank you. Initialization completed.

https://www.ideone.com/ZiOpGH

最佳答案

catch (InputMismatchException e2)中,测试是否input.hasNextDouble()(或input.hasNextFloat()?不确定)哪一个更普遍......)是正确的。如果是,那么您可以区分“用户输入 double ”和“用户输入非数字类型”的情况

关于java - 如何创建检查 int 范围、数字类型而不是 char 的异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15468418/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com