Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
603 views
in Technique[技术] by (71.8m points)

java - Scanner Exception Retry

How to make scanner retry when exception occur?
Consider this app running on CLI mode.

Example:

System.out.print("Define width: ");
    try {
        width = scanner.nextDouble();
    } catch (Exception e) {
        System.err.println("That's not a number!");
        //width = scanner.nextDouble(); // Wrong code, this bring error.
    }

If the user not inputting double type input, then the error thrown. But i want after the error message appears. It's should be asking the user input the width again.

How to do that?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If I understood you correctly, you want the program to ask the user to re-enter a right input after it fails. In that case you can do something like:

boolean inputOk = false;
while (!inputOk) {
    System.out.print("Define width: ");
    try {
        width = scanner.nextDouble();
        inputOk = true;
    } catch (InputMismatchException e) {
        System.err.println("That's not a number!");
        scanner.nextLine();   // This discards input up to the 
                              // end of line
        // Alternative for Java 1.6 and later
        // scanner.reset();   
    }
}

Note: you should only catch and retry for a InputMismatchException. The nextXxx methods throw other exceptions, and if you attempt to retry those, your application will go into an infinite loop.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...