7
\$\begingroup\$

I've written the below code to validate user input but I feel it's quite excessive for what seems to be a simple operation. I want to only accept non-negative integers or doubles as an input. This block of code is required three times in my program so I will need to put it into a method or something but in the mean time is there a simpler way to validate user input?

    Scanner input = new Scanner(System.in);

    boolean validWidth = false;
    double width = 0.0;;

    do // do while runs until the input is validated
    {
        System.out.print("Enter width: ");
        if (input.hasNextInt()) // we accept an int
        {
            width = input.nextInt();
            if (width > 0) // we accept a non-negative
            {
                validWidth = true;
            }
            else // refuse a negative 
            {
                System.out.println("Input error. Try again.");
                validWidth = false;
            }
        } 
        else if (input.hasNextDouble())// accept a double
        {
            width = input.nextDouble();
            if (width > 0) // we accept a non-negative
            {
                validWidth = true;
            }
            else // and refuse a negative 
            {
                System.out.println("Input error. Try again.");
                validWidth = false;
            }
        }
        else 
        {
            System.out.println("Input error. Try again.");
            validInput = false;
            input.next();
        }
    } while (!(validWidth));
\$\endgroup\$
3
  • \$\begingroup\$ Welcome to Code Review. Unfortunately, your code is missing some important context, for example input's type, how it's initialized, and the declarations of the other variables. Keep in mind that It's fine to drop a lot of code here, as long as you properly explain it beforehand. \$\endgroup\$
    – Zeta
    Mar 14, 2019 at 20:54
  • \$\begingroup\$ Sorry, I have added those now. \$\endgroup\$ Mar 14, 2019 at 20:59
  • \$\begingroup\$ Perfect, thanks. I hope that one of the Java devs will review your code soon. \$\endgroup\$
    – Zeta
    Mar 14, 2019 at 21:01

1 Answer 1

4
\$\begingroup\$

You are distinguishing between hasNextInt() and hasNextDouble() in the input stream, but treating them identically afterwards. hasNextDouble() will return true if the next token is an integer, because integers can be successfully parsed as a double too.

So your loop could be simplified into:

double width = 0.0;

for(;;) {
    System.out.print("Enter width: ");
    if (input.hasNextDouble()) {
        width = input.nextDouble();
        if (width > 0)
            break;
    }
    System.out.println("Input error. Try again.");
    input.nextLine();
}

A few notes:

  • The unnecessary validWidth variable has been removed. A break statement exits the infinite for(;;) loop, skipping over the "cleanup, try again" code.

  • .nextLine() is used to cleanup after invalid input. This is important, because if the user enters "one fish two fish red fish blue fish" instead of say -12, your current approach will print out "Input error. Try again" 8 times. Using .nextLine() discards everything up to and including the new line character. Which brings us to zero and negative numbers. If the user enters a valid integer/double, but not a positive one, your code didn't skip any tokens, where as my code (as mentioned above) will skip the remaining input up to and including the new line character. Assuming the next character was a new line (as in the user entered -12 and pressed the return key) the following .hasNextDouble() will skip over the new line (and any other blank space) looking for the next token, so the effect is approximately the same.

  • But my code performs differently if the user enters red 5. You original code will print "Invalid input. Try again.", and then immediately consume the 5 as valid input, where as my code will discard the remainder of the line, and wait for the user to enter another line.

Since you are using the code multiple places, putting it into a method is prudent. Here is one using a DoublePredicate functional interface in order to validate the input according to the caller's requirements:

double getDouble(Scanner input, String prompt, DoublePredicate validate) {
    double value = 0.0;

    for(;;) {
        System.out.print(prompt);
        if (input.hasNextDouble()) {
            value = input.nextDouble();
            if (validate.test(value))
                return value;
        }
        System.out.println("Input error. Try again.");
        input.nextLine();
    }
}

Which you could use with a lambda function like:

    double width = getDouble(input, "Enter width: ", x -> x > 0);
\$\endgroup\$
1
  • \$\begingroup\$ Nice explanation Amazing (-_-) \$\endgroup\$
    – Onic Team
    Mar 15, 2019 at 5:25

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.