简体   繁体   中英

User input validation for JOptionPane.showInputDialog

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!

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

}

Read the section from the Swing tutorial on How to Make Dialogs , which actually shows you how to use JOptionPane easily so you don't need to validate the input.

There are different approaches your could use. You could use a combo box to display the choices or maybe multiple buttons to select a choice.

The tutorial also shows you how to "Stopping Automatic Dialog Closing" so you can validate the users input.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM