Reputation: 56509
This piece of code is supposed to get an integer number from user and then finish the program. If the user inputs an invalid number, it asks user again.
After catching exception, it uses Scanner.reset()
to reset the scanner, but it doesn't work. and it re-throws previous exception.
Scanner in = new Scanner(System.in);
while (true) {
try {
System.out.print("Enter an integer number: ");
long i = in.nextLong();
System.out.print("Thanks, you entered: ");
System.out.println(i);
break;
} catch (InputMismatchException ex) {
System.out.println("Error in your input");
in.reset(); // <----------------------------- [The reset is here]
}
}
I thought Scanner.reset()
will reset everything and forget the exception. I put it before asking the user for a new input.
If I get the point wrong, what is the right way?
Upvotes: 8
Views: 7294
Reputation: 726849
You misunderstood the purpose of the reset
method: it is there to reset the "metadata" associated with the scanner - its whitespace, delimiter characters, and so on. It does not change the state of its input, so it would not achieve what you are looking for.
What you need is a call of next()
, which reads and discards any String
from the Scanner
:
try {
System.out.print("Enter an integer number: ");
long i = in.nextLong();
System.out.print("Thanks, you entered: ");
System.out.println(i);
break;
} catch (InputMismatchException ex) {
System.out.println("Error in your input");
in.next(); // Read and discard whatever string the user has entered
}
Relying upon exceptions to catch exceptional situations is OK, but an even better approach to the same issue would be using has...
methods before calling the next...
methods, like this:
System.out.print("Enter an integer number: ");
if (!in.hasNextLong()) {
in.next();
continue;
}
long i = in.nextLong();
System.out.print("Thanks, you entered: ");
System.out.println(i);
break;
Upvotes: 12
Reputation: 5291
Per Scanner.reset() javadoc, the method only "resets" locale, radix and delimiter settings. It does not do anything to the data it already read.
Upvotes: 3