Scanner(System.in) infinite loop

Why I'm getting infinite loop in recursion method, without a chance to input any symbol to break it?

class Test {
   int key=0;
   void meth(){
     System.out.println("Enter the number here: ");
     try(Scanner scan = new Scanner(System.in)) {
        key = scan.nextInt();
        System.out.println(key+1);
     } catch(Exception e) {
        System.out.println("Error");
        meth();
     }
   }
}

class Demo {
  main method {
    Test t = new Test();
    t.meth();
  }
} 

If you try to create an error (putting string value in key and then try to add to it a number), you will get infinite "Error" text in console, instead of that, after first error, program should ask again the number and only then decide what to do.

Jon Skeet
people
quotationmark

If nextInt() fails, it throws an exception but doesn't consume the invalid data. From the documentation:

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.

You're then recursively calling meth() again, which will try to consume the same invalid data a second time, fail again (without consuming it), and recurse.

Firstly, I wouldn't use recursion here in the first place. Prefer a simple loop. Next, if you have invalid input you should consume it appropriately before trying again. Finally, consider using hasNextInt instead of just using nextInt and catching the exception.

So maybe something like this:

import java.util.Scanner;

class Test {
   public static void main(String[] args){
       try (Scanner scanner = new Scanner(System.in)) {
           System.out.println("Enter the number here:");
           while (!scanner.hasNextInt() && scanner.hasNext()) {
               System.out.println("Error");
               // Skip the invalid token
               scanner.next();
           }
           if (scanner.hasNext()) {
               int value = scanner.nextInt();
               System.out.println("You entered: " + value);
           } else {
               System.out.println("You bailed out");
           }
       }
   }
}

people

See more on this question at Stackoverflow