简体   繁体   English

使用JOptionPane进行输入验证

[英]Input Validation with JOptionPane

I'm doing input validation on a program using JOptionPane boxes. 我正在使用JOptionPane框对程序进行输入验证。 I'm trying to have the input box repeat after the error message every time the user enters in a non-double. 我试图在每次用户输入非双重错误消息后重复输入框。 How would I do this? 我该怎么做?

    try {
        lengthResult = Double.parseDouble(JOptionPane.showInputDialog("What is the length of your garage in square feet?"));
    }
    catch (NumberFormatException e) {
        JOptionPane.showMessageDialog(null, "Please enter a number in digit format.","Inane error",JOptionPane.ERROR_MESSAGE);
    }

If you want to repeat the message box until the user enters something valid, I'd go like this: 如果你想重复消息框,直到用户输入有效的内容,我会这样:

Double lengthResult = null; //Init to null, which is invalid
String title = "Please anter a number";
int initialType = JOptionPane.QUESTION_MESSAGE;
do {
  try {
    lengthResult = Double.parseDouble(
      JOptionPane.showInputDialog(null,
         "What is the length of your garage in square feet?",
         title, initialType));
  } catch (NumberFormatException e) {
    initialType = JOptionPane.ERROR_MESSAGE;
    title = "Error: Please enter a number!";
  }
} while(lengthResult == null); //Iterate as long as no valid input found

Note that this check relies on lengthResult being an Object of type Double, not a primitive type double. 请注意,此检查依赖于lengthResult是Double类型的Object,而不是基本类型double。 With primitive double you'd need some extra flag as you cannot check on lengthResult value this way. 对于原始double,你需要一些额外的标志,因为你无法通过这种方式检查lengthResult值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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