【问题标题】:How to retry input after an InputMismatchException?如何在 InputMismatchException 后重试输入?
【发布时间】:2016-09-12 21:36:35
【问题描述】:

我正在创建一个接受用户输入的程序。现在我想在用户输入无效命令时重新运行输入选项。像这里只有整数输入是首选但如果用户输入文本,那么我想捕获异常并重新运行该方法。

我已经尝试过了,但它让我陷入了无限循环。实现这一目标的最佳方法是什么。如果有人在这方面帮助我,那就太好了。

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




        }

    }

【问题讨论】:

标签: java validation exception try-catch user-input


【解决方案1】:

如果您输入的不是整数,nextInt() 将抛出异常,输入的内容仍将在输入缓冲区中,因此下次调用nextInt() 时,您将读取相同的错误输入。您应该首先调用hasNextInt() 来查看输入是否为整数;如果没有,只需调用nextLine() 跳过错误输入(并写一条消息告诉用户重试)。

或者你可以在 catch 块中调用scanner.nextLine()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多