0

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.

0

3 Answers 3

2
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

Sign up to request clarification or add additional context in comments.

2 Comments

Forgot about the %f... thanks! I was pretty certain it was something with the input. the flushing makes sense and its exactly what I was looking for.
Don't forget %n too, or your output will all be on one line. printf doesn't add a newline automatically.
1

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

2 Comments

Thank you! answer is correct :) I never thought about consuming the invalid input I just kind of figured it was done. Will definitely keep it in mind though when using scanners in the future.
@helpme You are welcome. If you are not that familiar yet with Scanner than you probably should also read this stackoverflow.com/questions/13102045/… to avoid confusion in the future :)
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.