javatry-catchinputmismatchexception

input miss match control in java with try catch


i wrote this code to control input so user cannot enter anything except integers but problem is that: when an Exception occures, the message in Exception block is continousely printed and never ends, what i can do ?

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    int i=0;
    boolean success = false;
    
    System.out.println("Enter an int numbers :");
    
    while(!success) {//"while loop" will continue until user enters an integer
        try {
            i = scanner.nextInt();
            success=true;//if user entered an integer "while loop" will end, or if user entered another type Exception will occur
            
        }catch(InputMismatchException e) {
            System.out.println(" enter only integers ");
        }
    }
    System.out.println(i);
}

Solution

  • Add scanner.nextLine(); in your try and catch block. Like this

    while(!success) {//"while loop" will continue until user enters an integer
            try {
                i = scanner.nextInt();
                success=true;//if user entered an integer "while loop" will end, or if user entered another type Exception will occur
                scanner.nextLine();
                
            }catch(InputMismatchException e) {
                System.out.println(" enter only integers ");
                scanner.nextLine();
            }
        }
    

    You can also add just one scanner.nextLine() in the finaly block, which should be below catch