I'm having trouble with my exception handling. The program runs fine if I input a number but create an infinite loop if a character is entered.
boolean ask= true;
while(ask)
{
ask = false;
try
{
System.out.println("What is the age?");
int age = input.nextInt();
setAge(age);
}catch(InputMismatchException e) {
System.out.println("Invalid input!");
ask = true;
}
}//end while
Let's say you enter "abc"
Your call to input.nextInt()
causes the scanner to look at the a
and say "That's not an int, so I will throw an exception."
In the exception handler, you set ask
to true
so the loop repeats.
When the loop repeats, the scanner looks at that exact same a
again, and it says "That's not an int, so I will throw an exception."
In the exception handler, you set ask
to true
so the loop repeats.
And so on....
That pesky a
never gets consumed by the scanner.
Try below code:
boolean ask= false;
while(!ask)
{
try
{
System.out.println("What is the age?");
int age = input.nextInt();//does not read the newline character in your input created by hitting "Enter,"
setAge(age);
ask = true;
}catch(InputMismatchException e) {
System.out.println("Invalid input!");
input.nextLine();//consumes the \n character
}
}//end while
From the source code of nextInt:
public int nextInt(int radix) {
// Check cached result
if ((typeCache != null) && (typeCache instanceof Integer)
&& this.radix == radix) {
int val = ((Integer)typeCache).intValue();
useTypeCache();
return val;
}
setRadix(radix);
clearCaches();
// Search for next int
try {
String s = next(integerPattern());
if (matcher.group(SIMPLE_GROUP_INDEX) == null)
s = processIntegerToken(s);
return Integer.parseInt(s, radix);
} catch (NumberFormatException nfe) {
position = matcher.start(); // don't skip bad token
throw new InputMismatchException(nfe.getMessage());
}
}
It uses Integer.parseInt(s, radix);
to produce the result.
If call Integer.parseInt("s");
will result:
Exception in thread "main" java.lang.NumberFormatException: For input string: "s"
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.