Scanner nextInt() causing endless error inside a loop [duplicate]

  • A+
Category:Languages

The following code output endless errors, when a user entered not a number.

Scanner scn = new Scanner(System.in); System.out.println("Enter the number: ");    int n = 0;   while(true){     try {         n = scn.nextInt();     } catch (Exception e) {         e.printStackTrace();         continue;     }     break; } 

I expect that the code wait for new input when user entered not a number.

 


From the javadoc,

When a Scanner throws an InputMismatchException, the scanner will not pass the token that caused the exception, so that it may be retrieved or skipped via some other method.

In your case, scn.nextInt() must have thrown InputMismatchException. But the token is not passed (in other words,the input token hangs in there to be passed by Scanner). So on the next iteration of the loop, scn.nextInt() reads the same token again and throws the exception again resulting in an infinite loop.

If you inspect the value of CharBuffer (HeapCharBuffer?) inside the Scanner object, it still contains the input you have typed the first time and causing this issue. Also, you cannot explicitly clear Scanner's buffer.

Also, beware of resource-leaks!

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: