Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Beginner - Infinite Loop with Scanner Object

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?

like image 844
Lindstorm Avatar asked May 09 '26 07:05

Lindstorm


1 Answers

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.

like image 165
moh ro Avatar answered May 10 '26 20:05

moh ro



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!