The first example from Input validation correctly handles any invalid integer input (ex: -5, 15). If the user enters input that is not an integer (ex: hamster), nextInt crashes with an InputMismatchException.

Handling (invalid) input other than integers requires accepting the input as a String.

Option 1 isInt method

public static boolean isInt(String str)
{
    try
    {
        Integer.parseInt(str);
        return true;
    }
    catch(NumberFormatException e)
    {
        return false;
    }
}

isInt returns true if str is an int, false otherwise. isInt runs Integer.parseInt. If parseInt does not throw a NumberFormatException, str is an int. The value returned by parseInt is ignored.

Input validation using isInt

System.out.print("Enter an integer from 1 to 10 (inclusive): ");
String input = fromKeyboard.nextLine();

while( ! isInt(input) ||
        Integer.parseInt(input) < 1 ||
        Integer.parseInt(input) > 10)
{
    System.out.println("\nInvalid input");
    
    System.out.print("Enter an integer from 1 to 10 (inclusive): ");
    input = fromKeyboard.nextLine();
}

System.out.println(Integer.parseInt(input) + " is valid");

As with all input validation, the while condition evaluates to true if the input is not valid. The input is not valid if it is not an int or if it is out of range.

This example prints the input, so it is not strictly necessary to parse the input as an int on the last line. In practice, the valid input would typically be returned or used later in the program, which would require parsing the valid input as an int.

Option 2 asInt method

public static int asInt(String str, int valueIfNotInt)
{
    try
    {
        return Integer.parseInt(str);
    }
    catch(NumberFormatException e)
    {
        return valueIfNotInt;
    }
}

asInt parses str as an int and returns the int value. If str is not an int, asInt returns valueIfNotInt. Although asInt is more complex than isInt, it can be used to avoid repeatedly parsing the String input to an int.

Input validation using asInt

final int INVALID_VALUE = -1;

System.out.print("Enter an integer from 1 to 10 (inclusive): ");
int input = asInt(fromKeyboard.nextLine(), INVALID_VALUE);

while(input < 1 || input > 10)
{
    System.out.println("\nInvalid input");
    
    System.out.print("Enter an integer from 1 to 10 (inclusive): ");
    input = asInt(fromKeyboard.nextLine(), INVALID_VALUE);
}

System.out.println(input + " is valid");

Most of this code is the same as the original input validation. The input is taken as a String and immediately converted to an int using asInt. INVALID_VALUE can be set to any value that is not within the valid range. The while condition will already reject INVALID_VALUE, so it does not need to be modified.

Handling double input

Both approaches can be used to accept input of type double. Double.parseDouble replaces Integer.parseInt. The NumberFormatException is the same.

Comments

Comment on Input validation as String