user3738313
user3738313

Reputation: 3

Continually Validating Integers

I have a method I'm using to validate user-inputted values in a program. Whenever the user inputs a string into a JOptionPane, I call this method and pass in the inputted string, plus the maximum and minimum values I need their input to be between. First I check if the input is an integer by trying to parse the input string and catching exceptions, then I check if the integer is between the min and max. My problem is that if the user inputs another incorrect non-integer value after being prompted, I don't know how to check if the new value is correct or not. Here is the method, can anybody help?

int checkInput(String input, int min, int max) {
        Boolean isInteger = false;
        Boolean inputAccepted = false;
        int userInput = 0; //will be set later
        while (!isInteger) {
            try
            {
                userInput = Integer.parseInt(input);
            }
            catch (NumberFormatException e)
            {
                userInput = Integer.parseInt(JOptionPane.showInputDialog("Please enter only integers between " + min + " and "+ max + "."));
                isInteger = true; //the problem here is that it assumes the user inputted a correct value after being prompted... what if they enter another incorrect value?
            }
        }
        while (!inputAccepted) {
        if (userInput < min || userInput > max) 
        {
                userInput = Integer.parseInt(JOptionPane.showInputDialog("Please enter only integers between " + min + " and "+ max + "."));
        }
        else 
        {
            inputAccepted = true;
        }
        }
        return userInput;
    }

Upvotes: 0

Views: 65

Answers (2)

brummfondel
brummfondel

Reputation: 1210

Your checkInput() function should throw its own exception if the input is not correct. Spliting the code into a validator and a parser would result in parsing the input twice.

Upvotes: 0

ajb
ajb

Reputation: 31689

I believe the main problem is that you have a method whose job isn't simple and well-defined. It looks like you have a statement outside this method that inputs a number; but checkInput has two jobs: making sure the number is valid, and inputting more numbers until it is. This is a problem in two ways: your code that does the input is duplicated in two places, and you have a method whose responsibility isn't clear.

Instead, try writing a method that just checks whether the input is valid, and returns true or false. I'd change the name to isValidInput. The caller would then have a loop that would perform the input, make sure it's valid, and go back if it isn't.

Usually I wouldn't answer a question like this by pointing to flaws in your design. But I think that in this case, if you rethink your design, your question will answer itself. (That's often the case when you design things correctly--things fall into place.)

Upvotes: 2

Related Questions