User input validation for JOptionPane.showInputDialog

Perd picture Perd · Aug 23, 2010 · Viewed 18.3k times · Source

I'm just learning JAVA and having a bit of trouble with this particular part of my code. I searched several sites and have tried many different methods but can't seem to figure out how to implement one that works for the different possibilities.

int playerChoice = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter number for corresponding selection:\n"
                + " (1) - ROCK\n (2) - PAPER\n (3) - SCISSORS\n")) - 1;

I imagine I need to have some type of validation even for when the user has no input as well as an input that is not 1, 2 or 3. Anyone have suggestions on how I can accomplish this?

I tried a while loop, an if statement to check for null before converting the input to an integer, as well as a few different types of if else if methods.

Thanks in advance!

Answer

Paul Jowett picture Paul Jowett · Aug 23, 2010

You need to do something like this to handle bad input:

boolean inputAccepted = false;
while(!inputAccepted) {
  try {
    int playerChoice = Integer.parseInt(JOption....

    // do some other validation checks
    if (playerChoice < 1 || playerChoice > 3) {
      // tell user still a bad number
    } else {
      // hooray - a good value
      inputAccepted = true;
    }
  } catch(NumberFormatException e) {
    // input is bad.  Good idea to popup
    // a dialog here (or some other communication) 
    // saying what you expect the
    // user to enter.
  }

  ... do stuff with good input value

}