In the following code, I get an infinite loop if an enter anything that causes an InputMismatchException in the try part below
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
double x;
boolean b = true;
while (b) {
try {
x = in.nextDouble(); //Enter 4a
b = false;
} catch (InputMismatchException e) {
System.out.println("Wrong");
// in.nextLine();
}
}
in.close();
}
If I uncomment the in.nextLine();, the code works fine. I am wondering why there is an infinite loop. I do not see why there would be an infinite loop because after the catch part is executed, I should be able to enter data when the try part is executed again. Why does this not happen?
Scanner maintains a position variable.
// The index into the buffer currently held by the Scanner
private int position;
In case of the exception the position value doesn't get updated and the scanner keeps trying to read from the same position containing your invalid token.
in.nextLine()
The above line moves the position variable past the incorrect token and is ready to read fresh data in the buffer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With