Search code examples
javaeclipsevalidationinputdouble

How to reprompt user to put a valid input when user inputs a String (Java)


The program should give the output "Invalid Input" when the user inputs a string (eg. "thirty"), then prompt the user to type a valid input. When I type a string, I get the error message Exception in thread "main" java.util.InputMismatchException when inputting a string.

 public static void main(String[] args) {
    double wallHeight = 0.0;

    boolean valid = true;

    // Implement a do-while loop to ensure input is valid
    // Prompt user to input wall's height
    do {
        System.out.println("Enter wall height (feet): ");
        wallHeight = scnr.nextDouble();
        valid = true;
        if (wallHeight <= 0) {
            System.out.println("Invalid Input");
            valid = false;
        }
     } while (!valid);  

Solution

  • According to the documentation for Scanner.nextDouble():

    InputMismatchException - if the next token does not match the Float regular expression, or is out of range

    This means that if the user types in non-numeric characters, nextDouble() will throw this exception.

    To allow your program to continue, you need to catch the exception and print out an error message. You can do this with a try...catch statement. I won't get into the details here since there are a lot of resources already available about how to do this.

    Alternatively, you can use Scanner.hasNextDouble() to check for a double value first.

    The links I gave are all from the official Java API documentation from Oracle. I strongly encourage you to familiarize yourself with these docs. They explain all of the detail you need for each standard Java class.