0

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();           
            } 
        }
    }
}
3
  • 3
    What is menuPrinc();? If you want to restart something, use an actual loop, not recursion Commented May 10, 2016 at 11:57
  • i think you just have to call menu() in the catch block Commented May 10, 2016 at 12:00
  • menuPrinc() is the menu() method , I forgot to correct it,sorry! Commented May 10, 2016 at 12:02

3 Answers 3

1

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();

} 
Sign up to request clarification or add additional context in comments.

2 Comments

the only problem is that the errorr message can't be seen , it jumps straight without showing it .
Thats because error message and menu display are in quick succession.. to mitigate this issue you can put Thread.sleep just before menu call
1

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.