捕获InputMismatchException直到它正确[重复]

问题描述 投票:3回答:4

我正在尝试向我的程序添加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只是数字”。

我该如何正常工作?

java loops exception-handling
4个回答
2
投票

请注意When a scanner throws an InputMismatchException, the scanner will not pass the token that caused the exception, so that it may be retrieved or skipped via some other method.

为了避免“无限循环”,客户ID只是数字“。”,您需要在catch语句中调用input.next();,以便可以在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

1
投票

发生的事情是你捕获不匹配,但仍然需要清除数字“错误的输入”并且应该调用.next()。编辑:因为您还要求每个do / while大于或等于1

boolean valid = false;
while(!valid) {
    try {
        custID = input.nextInt();
        if(custID >= 1) //we won't hit this step if not valid, but then we check to see if positive
            valid = true; //yay, both an int, and a positive one too!
    }
    catch (InputMismatchException e) {
        System.out.println("Customer IDs are numbers only");
        input.next(); //clear the input
    }
}
//code once we have an actual int

0
投票

为什么不使用扫描仪对象用Scanner.readNextInt()读取它?


0
投票

我明白了,这是你正在寻找的解决方案:

public class InputTypeMisMatch {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int custID=0;
        System.out.println("Please enter a number");
        while (!input.hasNextInt()) {
            System.out.println("Please enter a number");
            input.next();
        }
        custID = input.nextInt();
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.