简体   繁体   中英

Java try catch (InputMismatchException) unexpected loop

Im trying to catch an InputMismatchException it works at the first interraction , but when the menu() method is called again , it starts looping until it gets stuck in an error.

In the try catch my objective was to get an error message and after that start the menu() method again.

I have the following code:

public class Menu extends ProfilesManager {
    static Scanner sc = new Scanner(System.in);

    public static void menu() {

        int number;
        System.out.println("** Welcome... **\n  ");
        System.out.println("* what you wanna do?:\n");
        System.out.println("(1) Login  \n(2) Register  \n(3) Find User  \n(4) Exit\n");
        System.out.print("-Answer?: ");

        try {
            number = sc.nextInt();            
            if (number == 1) {
                Login();
            } else if (number == 2) {
                Register(); 
            } else if (number == 3) {
                FindUser(); 
            } else if (number== 4) {
                Exit();
            }                                                    
        } catch (InputMismatchException e) {   
            System.out.println("Error , only numbers!!");
            menu();           
            } 
        }
    }
}

You have infinite recursion. You gotta move menu() out of the catch block if you want to call it again. Otherwise it's infinite loop.

This is because once you enter a wrong input. you are not clearing it and Scanner will keep on reading it and every time it will give you InputMisMatchException

You need to clear it in your catch block

}catch(InputMismatchException e){

    System.out.println("Error , only numbers!!");
    sc.nextLine();
    // Put 2 second delay
    try{
         Thread.sleep(2000);
    }catch(InterruptedException ex){
       ex.printStackTrace();
    }
    menu();

} 

I guess you should write sc = new Scanner(System.in); after System.out.println("Error , only numbers!!");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM