1

Why I'm having an infinite loop when I enter a non-digit token?

public class ExceptionHandling {
    static int i;
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        boolean b=true;
        Scanner in=new Scanner(System.in);
        while (b ==true) { 
            try{
                i=in.nextInt();
                b=false;
                // System.out.println("not executrd bcoz above exception");
            }
            catch(InputMismatchException e){      
                System.out.println(i);
            }     
        }            
    }
}
Arjun Chaudhary
  • 2,163
  • 2
  • 14
  • 30

1 Answers1

2

You're actually asking "why my code runs to infinite loop when I enter a non-integer input".

Well, you need to call in.next() in the catch clause to solve this. Why? See the Scanner docs:

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.

Maroun
  • 87,488
  • 26
  • 172
  • 226