Skip to content
Advertisement

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);

Advertisement

Answer

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);
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement