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) {
        ...
    }
}
mbomb007
  • 3,788
  • 3
  • 39
  • 68
wadda_wadda
  • 966
  • 1
  • 8
  • 29
  • 1
    Can you be more specific? What kind of validation are you talking about? While in while loop? – Crazyjavahacking Jan 27 '15 at 19:12
  • You may chechk this document: http://www.cse.yorku.ca/~mack/1011/InputValidation.PDF – pcejrowski Jan 27 '15 at 19:20
  • In the example you gave, your loop is clear and will perform about as well as you can hope (and as fast as you need, given that the bottleneck will be the human), so just go with it. Absolutes like "never use goto-like constructs" aren't always right. People also say not to use exceptions as control flow, but in this case you more or less have to, because of how `Integer.parseInt` works. (I guess you could duplicate its logic to pre-validate the string before parsing it, but you don't want to do that.) – yshavit Jan 27 '15 at 19:22
  • 1
    That is an odd dup to mark this as. If anything I would have marked it as a dup of http://stackoverflow.com/questions/6456219/java-checking-if-parseint-throws-exception but in reality it is slightly different than both of those questions. – chancea Jan 27 '15 at 19:30
  • 2
    This is not a duplicate. – mbomb007 Jan 27 '15 at 19:31
  • 2
    For the record, I voted to close as primarily opinion-based, not as a dupe. – yshavit Jan 27 '15 at 19:49

1 Answers1

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:");
    }
}
mbomb007
  • 3,788
  • 3
  • 39
  • 68
  • 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?). – yshavit Jan 27 '15 at 19:50