验证输入对话框

Jam*_*mes 5 java swing joptionpane

嗨,我觉得相当愚蠢,因为我应该能做到这一点,但我做不到!我也在网上和我的书中检查过,这么简单的事情没什么(或者我可以看到它).

我想做的是向用户提供JOptionPane.showInputDialog(null,...并检查

  1. 它不是空白
  2. 它不包含数字或特殊字符,例如/> <.!"£$%^&*()

如果它没有通过任何这些测试重新显示框,所以他们必须这样做,欧元这是一个简单的事情,但我只是无法解决它:(

我的愚蠢请怜悯!在此先感谢任何帮助它是合适的!

Osk*_*und 2

有一个方法可以显示输入对话框,验证输入,如果可以则返回输入,否则它会调用自身重复该过程,直到输入有效。像这样的东西:

private String showInputDialog()
{
    String inputValue = JOptionPane.showInputDialog("Please input something");

    if(inputValue == null || inputValue.isEmpty() || !inputValue.matches("[A-Za-z]*"))
    {
        inputValue = showInputDialog();
    }

    return inputValue;
}
Run Code Online (Sandbox Code Playgroud)

其中!inputValue.matches("[A-Za-z]*")将在除任意数量的字母 a 到 z(大写或小写)之外的任何输入上触发。

然后从您的代码中您只需调用它并使用返回值执行您想要的任何操作。

String input = showInputDialog();
System.out.println(input);
Run Code Online (Sandbox Code Playgroud)