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