How to retry input after an InputMismatchException

2019-03-04 06:18发布

I am creating a program that takes input from the user.Now I want to re-run the input option if a user enters an invalid command. Like here only integer input are preferred but if the user inputs text, then I want to catch the exception and rerun the method.

I have tried this but it turns me into an infinite loop.What would be the best way to achieve this. It would be great if someone helps me on this.

    boolean retry = true;

    while(retry){

        try{
            //considering response from the user
            System.out.print("\nEnter Your Command : ");
             f_continue =  processresponse(scanner.nextInt());
             retry = false;
        }catch(InputMismatchException e){

            System.err.println("\nPlease Input a Valid Command from 1-5 or 0 for Exit");




        }

    }

1条回答
Summer. ? 凉城
2楼-- · 2019-03-04 06:37

If you enter something other than an integer, nextInt() will throw an exception, and what was entered will still be in the input buffer, so the next time you call nextInt(), you will read the same bad input. You should first call hasNextInt() to see if the input is an integer; if not, just call nextLine() to skip the bad input (and write a message telling the user to re-try).

Or you can just call scanner.nextLine() in the catch block.

查看更多
登录 后发表回答