编程语言
首页 > 编程语言> > java-捕获InputMismatchException,直到它正确为止

java-捕获InputMismatchException,直到它正确为止

作者:互联网

这个问题已经在这里有了答案:            >            How to handle infinite loop caused by invalid input (InputMismatchException) using Scanner                                    5个
>            How to use Scanner to accept only valid int as input                                    6个
我正在尝试在程序中添加catch块以处理输入不匹配异常.我设置了第一个在do while循环中工作的程序,以便为用户提供纠正问题的机会.

System.out.print("Enter Customer ID: ");
int custID=0;
do {
    try {
        custID = input.nextInt();
    } catch (InputMismatchException e){
        System.out.println("Customer IDs are numbers only");
    }
} while (custID<1);

就目前而言,如果我尝试输入字母,则会陷入“客户ID仅是数字”的无限循环.

我如何使它正常工作?

解决方法:

请注意,当扫描程序引发InputMismatchException时,扫描程序将不会传递导致异常的令牌,以便可以通过其他方法检索或跳过该令牌.

为了避免““客户ID仅是数字”的无限循环.”,您需要调用input.next();.在catch语句中,以便可以在Console中重新输入数字

声明

catch (InputMismatchException e) {
            System.out.println("Customer IDs are numbers only");

catch (InputMismatchException e) {
            System.out.println("Customer IDs are numbers only");
            input.next();
        }

测试示例:

Enter Customer ID: a
Customer IDs are numbers only
b
Customer IDs are numbers only
c
Customer IDs are numbers only
11

标签:loops,exception-handling,java
来源: https://codeday.me/bug/20191122/2060049.html