User input validation for JOptionPane.showInputDialog

感情迁移 提交于 2019-12-19 07:54:39

问题


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!


回答1:


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

}




回答2:


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.



来源:https://stackoverflow.com/questions/3544521/user-input-validation-for-joptionpane-showinputdialog

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!