简体   繁体   English

Java尝试捕获(InputMismatchException)意外循环

[英]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. 我试图捕获一个InputMismatchException它在第一种InputMismatchException下起作用,但是当再次调用menu()方法时,它开始循环,直到陷入错误。

In the try catch my objective was to get an error message and after that start the menu() method again. try catch我的目标是得到一条错误消息,然后再次启动menu()方法。

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. 如果要再次调用,必须将menu()从catch块中移出。 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 您没有清除它, Scanner会继续读取它,每次它都会给您InputMisMatchException

You need to clear it in your catch block 您需要在catch块中清除它

}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); 我猜你应该写sc = new Scanner(System.in); after System.out.println("Error , only numbers!!"); System.out.println("Error , only numbers!!");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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