Skip to main content
Engineering LibreTexts

13.7: Validating Input

  • Page ID
    18821
  • Here is a method that uses printLogarithm from the previous section:

    public static void scanDouble(Scanner in) {
        System.out.print("Enter a number: ");
        double x = in.nextDouble();
        printLogarithm(x);
    }
    

    This example uses nextDouble, so the Scanner (provided by the main method) tries to read a double. If the user enters a floating-point number, the Scanner converts it to a double. But if the user types anything else, the Scanner throws an InputMismatchException.

    We can prevent this error by checking the input before parsing it:

    public static void scanDouble(Scanner in) {
        System.out.print("Enter a number: ");
        if (!in.hasNextDouble()) {
            String word = in.next();
            System.err.println(word + " is not a number");
            return;
        }
        double x = in.nextDouble();
        printLogarithm(x);
    }
    

    The Scanner class provides hasNextDouble, which checks whether the next token in the input stream can be interpreted as a double. If so, we can call nextDouble with no chance of throwing an exception. If not, we display an error message and return.