简体   繁体   中英

Prevent user from inputting value larger than int max?

I have some cool code that takes an int value. I let my little brother test it, and what is the first thing he does? He enters this:

12345678910

And he got this error:

User did not input a number. (Error Code 1)

Well that's not true. Is there a way to give him a different error for "value too large"? Here's my code:

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

Thanks!

EDIT

The code that was posted that I used has been modified. This is the code I ended up going with, but the solution is no longer in the comments.

        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);
        }

Thank you to Jay Harris for solving my issue!

EDIT THE SECOND

I added a 'less than zero' check. In case anyone else stumbles upon this question wanting similar help, I'll show the updated code here:

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);
}

There is plenty of ways to achieve this, for instance check for a larger number and validate it against the max and min size of a Integer using Integer.MAX_VALUE and 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;
}

Try using the Scanner.hasNextInt() method:

From http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#hasNextInt()

Returns true if the next token in this scanner's input can be interpreted as an int value in the default radix using the nextInt() method. The scanner does not advance past any input.

if (input.hasNextInt()) {
    number = input.nextInt();
} else {
    System.err.println("User did not input a number. (Error Code 1)");
    System.exit(1);

}

If you want to detect that a number was entered, but that it might be too large to parse, try this approach:

   public static void main(String[] args) {

       Scanner input = new Scanner(System.in);
       System.out.println("Enter a number:");
       if (input.hasNextInt()) {
           int num = input.nextInt();
           System.out.println("num is " + num);
       } else {
           String s = input.next();
           boolean isaNumber = true;
           for (int i=0; i<s.length(); i++) {
               if (!Character.isDigit(s.charAt(i))) {
                   isaNumber = false;
                   break;
               }
           }
           if (isaNumber) {
               System.out.println("It appears you entered a number, but it canntot "
                    + "be read.  It might be too large.");
           } else {
               System.out.println("Error parsing number.");
           }
       }
   }

Here, I simply check if each character in the input is a digit. If so, I assume it is a number. This code could certainly be cleaned-up, and probably is not 100% bullet-proof. I just wanted to illustrate on possible approach to your question.

You could try to get a long instead, but that would only raise the limit, not solve the problem.

The other way would be to get the value as a String and check if its numeric using some regular expression befor trying to convert it. if the conversion fails then the number is to big.

As shown in this answer , you could store the input in a long instead, and then check if the number is too big. Or, you could just change all your values to a long type.

A large number will not return an exception from the compiler by itself; the error you ran into may be because an int cannot hold values exceeding around 2 billion. Instead you can try declaring number as a long type.

Another solution would be to first grab the input with a string, as @karfau stated. This could be done specifically by using the length() method; if the string exceeds a certain number of characters, you will know that the input is too long.

You could surround it with a try-catch block.

See the 1st answer to this question for more detailed info.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM