Home > other >  More succinct way to get Scanner input with error checking?
More succinct way to get Scanner input with error checking?

Time:03-11

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

CodePudding user response:

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

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

CodePudding user response:

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