Catching an InputMismatchException until it is correct [duplicate]

為{幸葍}努か 提交于 2020-06-12 07:10:48

问题


I am trying add catch blocks to my program to handle input mismatch exceptions. I set up my first one to work inside of a do while loop, to give the user the opportunity to correct the issue.

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

As it stands, if I try to enter a letter, it goes into an infinite loop of "Customer IDs are numbers only".

How do I make this work properly?


回答1:


Be aware that 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.

To avoid "infinite loop of "Customer IDs are numbers only".", You need to call input.next(); in the catch statement to to make it possible to re-enter number in Console

From

statement

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

To

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

Example tested:

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



回答2:


What's happening is that you catch the mismatch, but the number "wrong input" still needs to be cleared and a .next() should be called. Edit: since you also require it to be greater than or equal to 1 per your do/while

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



回答3:


Why not use a scanner object to read it with Scanner.readNextInt()?




回答4:


I got it, this is solution you are looking for:

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();
    }
}


来源:https://stackoverflow.com/questions/20075940/catching-an-inputmismatchexception-until-it-is-correct

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!