Reputation: 174
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();
}
}
}
}
Upvotes: 0
Views: 820
Reputation: 9946
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();
}
Upvotes: 1
Reputation: 529
I guess you should write sc = new Scanner(System.in);
after System.out.println("Error , only numbers!!");
Upvotes: 0
Reputation: 94
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.
Upvotes: 1