阻止用户输入大于int max的值?

Dig*_*can 2 java int exception max

我有一些很酷的代码,它采用int值.我让我的小弟弟测试一下,他做的第一件事是什么?他输入了这个:

12345678910
Run Code Online (Sandbox Code Playgroud)

他得到了这个错误:

User did not input a number. (Error Code 1)
Run Code Online (Sandbox Code Playgroud)

那不是真的.有没有办法给他一个"价值太大"的错误?这是我的代码:

try
{
    number = input.nextInt();
}
catch (InputMismatchException e)
{
    System.err.println("User did not input a number. (Error Code 1)");
    System.exit(1);
}
Run Code Online (Sandbox Code Playgroud)

谢谢!

编辑

我使用的已发布的代码已被修改.这是我最终使用的代码,但解决方案不再出现在评论中.

        try 
        {
            double intitalinput = input.nextDouble();

            if (intitalinput > Integer.MAX_VALUE)
            {
                System.err.println("User entered a number larger than " + Integer.MAX_VALUE + ". (Error Code 2)");
                System.exit(2);
            }
            else 
            {
                number = (int) intitalinput;
            }
        }
        catch (InputMismatchException e) 
        {
            System.err.println("User did not input a number. (Error Code 1)");
            System.exit(1);
        }
Run Code Online (Sandbox Code Playgroud)

感谢Jay Harris解决我的问题!

编辑第二

我加了一个'小于零'的支票.如果其他人偶然发现这个想要类似帮助的问题,我会在这里显示更新的代码:

try 
{
    double intitalinput = input.nextDouble();

    if (intitalinput > Integer.MAX_VALUE)
    {
        System.err.println("User entered a number larger than " + Integer.MAX_VALUE + ". (Error Code 2)");
        System.exit(2);
    }
    else if (intitalinput < 0)
    {
        System.err.println("User entered a number smaller than 0. (Error Code 3)");
        System.exit(3);
    }
    else 
    {
        number = (int) intitalinput;
    }
}
catch (InputMismatchException e) 
{
    System.err.println("User did not input a number. (Error Code 1)");
    System.exit(1);
}
Run Code Online (Sandbox Code Playgroud)

Jay*_*ris 5

有很多方法可以实现这一点,例如检查更大的数字并根据Integer使用Integer.MAX_VALUE和的最大和最小尺寸进行验证Integer.MIN_VALUE.

// long userInput = input.nextLong()
// or
double userInput = input.nextDouble();

// expecting an integer but user put a value larger than integer
if (userInput > Integer.MAX_VALUE || userInput < Integer.MIN_VALUE) {
   // Throw your error
}  else {
   // continue your code the number is an int
   number = (int) userInput;
}
Run Code Online (Sandbox Code Playgroud)