java JOptionPane.showInputDialog 的用户输入验证

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3544521/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 02:19:47  来源:igfitidea点击:

User input validation for JOptionPane.showInputDialog

javavalidationjoptionpane

提问by Perd

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.

我只是在学习 JAVA 并且在我的代码的这个特定部分遇到了一些麻烦。我搜索了几个站点并尝试了许多不同的方法,但似乎无法弄清楚如何实现一种适用于不同可能性的方法。

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?

我想即使在用户没有输入以及输入不是 1、2 或 3 的情况下,我也需要进行某种类型的验证。有人对我如何实现这一点有建议吗?

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.

我尝试了一个 while 循环,一个在将输入转换为整数之前检查 null 的 if 语句,以及几种不同类型的 if else if 方法。

Thanks in advance!

提前致谢!

回答by Paul Jowett

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

}

}

回答by camickr

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.

阅读 Swing 教程中关于如何制作对话框的部分,它实际上向您展示了如何轻松使用 JOptionPane,因此您无需验证输入。

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.

本教程还向您展示了如何“停止自动关闭对话框”,以便您可以验证用户输入。