Lindstorm
Lindstorm

Reputation: 889

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?

Upvotes: 4

Views: 338

Answers (4)

Randhawa
Randhawa

Reputation: 226

Reason for infinite loop is pointer(can be said position) which Scanner keeps to access the element and after accessing the element, pointer is advanced.

But When any of Scanner Method (i.e. , next() , nextDouble() ),throws an exception, you are still at the same position/pointer at which Scanner tried to access the element and exception has been thrown.

As you are already catching the Exception in catch statement but the pointer is still there (at the same position) which will continuously throw an exception, to avoid this, you must advance the pointer using .nextLine(). which will move pointer to next line for accepting next Input.

Upvotes: 0

moh ro
moh ro

Reputation: 86

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.

Upvotes: 1

curlyBraces
curlyBraces

Reputation: 1105

From Scanner javadoc:

Scans the next token of the input as a double. This method will throw InputMismatchException if the next token cannot be translated into a valid double value. If the translation is successful, the scanner advances past the input that matched.

So as MFisherKDX commented, the scanner advances only if the input is a valid double. Hence, the token has to be skipped programmatically.

Upvotes: 0

Kaushal28
Kaushal28

Reputation: 5557

So what in.nextLine(); does is consume the new line left over. In your case, when exception occurs, this is not performed and your code goes in infinite loop.

So either in.nextDouble() or in.nextLine() require to consume the line left over.

Upvotes: 0

Related Questions