简体   繁体   中英

Try/Catch looping in Java with user input

My code is supposed to take float value inputs from a user and once the user inputs 2 invalid inputs in a row (non float) the program stops and sums up the valid inputs and spits out the sum to the user. Here is the code: System.out.println("Please input a set of float values.");

    Scanner keyboard = new Scanner(System.in);
    int tries = 0;
    int maxTries = 2;
    double sum = 0;

    while (tries < 2) { 
        try {
             while (keyboard.hasNext()){
                 sum += keyboard.nextDouble();
                 tries = 0; // reset counter because of valid input
             }
        }
        catch (InputMismatchException e) {
            System.out.println("Invalid input. Float values "
                    + "only please.");
            tries += 1; // tries +1 because invalid input
        }
    }
    System.out.printf("The sum of your inputs is: %d", sum);

My exception is being thrown prematurely, once I put in one invalid input the program stops and sums up. I can't figure out how to allow the user two consecutive invalid (non float) inputs and then throw the exception. Thanks.

try{
        Scanner keyboard = new Scanner(System.in);
        int tries = 0;
        int maxTries = 2;
        double sum = 0;

        while (tries < 2) { 
            try {
                 while (keyboard.hasNext()){
                     double d = keyboard.nextDouble();
                     sum += d;
                     tries = 0; // reset counter because of valid input
                 }
            }
            catch (InputMismatchException e) {
                System.out.println("Invalid input. Float values "
                        + "only please.");
                tries += 1; // tries +1 because invalid input
                keyboard.nextLine();
            }
        }
        System.out.printf("The sum of your inputs is: %f", sum);
    }catch(Exception e){
        e.printStackTrace();
    }

The exception is thrown twice because there is still input in the keyboard scanner, and it attempts to continue reading. 'flush' it by reading in a nextline.

Also, on the output, print it with a %f

Scanner gives you hasNext and hasNextXXX where XXX is type you want precisely to avoid throwing exceptions.

Anyway if user provides invalid input it will stay in stream until you consume it. You can easily do it with next() or (sometimes better) with nextLine() method. So avoid using Exceptions as main part of your flow control logic .

So change your code and instead of hasNext which allows any kind of data, use hasNextDouble() .
BTW to print floating-point number you need to use %f , %d is for integers.

Scanner keyboard = new Scanner(System.in);
int tries = 0;
int maxTries = 2;
double sum = 0;

while (tries < maxTries) {
    if (keyboard.hasNextDouble()) {
        sum += keyboard.nextDouble();
        tries = 0; // reset counter because of valid input
    } else {
        System.out.println("Invalid input. Float values "
                + "only please.");
        keyboard.next();// consume one invalid token from user input
        tries += 1; // tries +1 because invalid input
    }
}
System.out.printf("The sum of your inputs is: %f", sum);

Example:

Input: 1 2 3 b 4 foo bar
Output:

1 2 a 3 a 4 aa a
Invalid input. Float values only please.
Invalid input. Float values only please.
Invalid input. Float values only please.
The sum of your inputs is: 10,000000

The easier way to handle this is to read each input line as a string (keyboard.nextLine). Then try Double.parseDouble to convert into a double, catchinh any NumberFormatException to check number of tries etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM