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

标签 java exception

我正在尝试解决异常问题,但我遇到的问题是我需要创建一个程序,要求用户输入数字 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/

相关文章:

java - 来自谷歌云存储的文件列表

java - 如何使用 bouncy caSTLe 在 Java 中创建 SHA512 摘要字符串?

java - 从技术上讲,您可以在 main 方法中调用 string[] 吗?

java - 具有多个数据源的 hibernate 配置类

c# - 使用语句不能正常工作

java - 应该过滤掉换行符的 if 语句不过滤换行符。

android - "Can' t compress a recycled bitmap”单个设备异常

c++ - 有没有办法让 DisableUserModeCallbackFilter 在 Windows 10 中工作?

java - 如何在输出页面中写入错误消息?

c++ - 抛出异常时使用 cout 语句尝试阻止行为