Getting problem in Input Mismatch Exception, it gets into infinity loop

Viewed 28

Why does this part keep going into infinite loop and not start from try block again asking for another input

catch (Exception e) { System.out.println(e); System.out.println(" enter integer only");

My code:

import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        boolean d = true;
        Scanner xc = new Scanner(System.in);
        while (d) {
            System.out.println("enter");
            try {
                int xa = xc.nextInt();
                d = false; 
               System.out.println(xa);
            } catch (Exception e) {
                System.out.println(e);
               System.out.println(" enter integer only");
           }
        }
     }
}

What I want this program to do is keep running until it gets an integer input, when given anything different like character it should display the exception, loop and ask for input again. But this code, when given different input, goes into infinity loop. Please help me rectify this logical error.

0 Answers
Related