0

It's been some years since I've used Java, and I'm not quite sure what the best practice for validating command line input is.

My code is currently structured like so:

while (true) {
    try { ... break; } catch(...) {...}
}

I feel that this is poor practice, because it's similar to using a goto statement in a way.

Is there a better way to validate user input?

Is simply using a boolean the preferred method?

Edit:

More specifically, validating user-input from the stdin (scanner).

Something to the extent of:

while(true){
    try {
        userInput = Integer.parseInt(stdin.next());
        break;
    } catch (InputMismatchException e) {
        ...
    }
}
6
  • 1
    Can you be more specific? What kind of validation are you talking about? While in while loop? Commented Jan 27, 2015 at 19:12
  • You may chechk this document: cse.yorku.ca/~mack/1011/InputValidation.PDF Commented Jan 27, 2015 at 19:20
  • 1
    That is an odd dup to mark this as. If anything I would have marked it as a dup of stackoverflow.com/questions/6456219/… but in reality it is slightly different than both of those questions. Commented Jan 27, 2015 at 19:30
  • 2
    This is not a duplicate. Commented Jan 27, 2015 at 19:31
  • 2
    For the record, I voted to close as primarily opinion-based, not as a dupe. Commented Jan 27, 2015 at 19:49

1 Answer 1

1

Though what you have is acceptable, I prefer to at least output a message if what they entered doesn't match your validation.

Something more like this:

int userInput;
System.out.println("Please enter an integer:");
while(true){
    try {
        userInput = Integer.parseInt(stdin.next());
        break;
    } catch (InputMismatchException e) {
        System.out.println("Please enter a valid integer:");
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

I would use the break rather than the valid flag, as the OP had originally. It has the same end effect, while being a bit simpler (why keep and update state you don't need?).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.