'More succinct way to get Scanner input with error checking?

Just want to know if there was any better way of doing this since it's a lot of writing.

boolean isInputValid = false;
do {
    System.out.print("Input: ");
    final String input = sc.nextLine();

    try {
        age = Integer.parseInt(input);
    } catch (NumberFormatException e) {
        System.out.println("Invalid input. Try again");
        continue;
    }

    if (input < 0 || 10 < input) {
        System.out.println("Number outside of range.");
    } else {
        isInputValid = true;
    }
} while (!isInputValid);


Solution 1:[1]

Well there are some things that can be ommited on a first look, but there is not much to remove.

  • Reduced integer parsing in a single line and removed input variable.
  • Change isInputValid to its negation isInputInvalid to remove else , Boolean assignment and negation in the while clause.
  • Moved if into the try clause to make redundant and remove the continue statement.
boolean isInputInvalid = true;
do {
    System.out.print("Input: ");
    try {
        age = Integer.parseInt(  sc.nextLine());
        isInputInvalid = input < 0 || 10 < input;
        if (isInputInvalid) {
           System.out.println("Number outside of range.");
        } 
    } catch (NumberFormatException e) {
        System.out.println("Invalid input. Try again");
    }
  
} while (isInputInvalid);

Solution 2:[2]

Well by first glance, I can see that you're comparing an incorrect variable type of string with an integer (your input variable), I'm just going to assume that you meant to compare the age. You should also put the if statements within your try/catch to ensure that its handled as intended (there's also no point in having it outside the try/catch if a NFE is thrown, it won't get ran anyways).

boolean isInputValid = true;
do {
            System.out.print("Input: ");
            final String input = sc.nextLine();

            try {
                age = Integer.parseInt(input);

                if (age < 0 || 10 < age) {
                    System.out.println("Number outside of range.");
                    isInputValid = false;
                }
            } catch (NumberFormatException e) {
                System.out.println("Invalid input. Try again");
                continue;
            }
        } while (isInputValid);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 softwarepie