JTextField 数据验证

JTextField Data Validation

Java 的新手,如有任何帮助,我们将不胜感激。 JTextField 中的数据验证存在一个小问题。 要求用户输入他们的年龄、是否吸烟以及是否超重。 吸烟和体重的验证工作正常,我设置的年龄限制也是如此。

但是,如果我在 ageField JTextField 中输入一个字母,它似乎会卡住并且不会打印其他验证错误。 (例如,它会正确打印 "Age must be an integer",但是如果我还在 smokesField 中输入 'h',则不会打印 "Smoke input should be Y, y, N or n"。)

抱歉,解释冗长臃肿!

无论如何,这是我遇到困难的代码,谢谢:

public void actionPerformed(ActionEvent e)
{
String ageBox = ageField.getText();
int age = 0;

if (e.getSource() == reportButton)
{
    if (ageBox.length() != 0)
        {
            try
            {
            age = Integer.parseInt(ageBox);
            }
            catch (NumberFormatException nfe)
            {
            log.append("\nError reports\n==========\n");    
            log.append("Age must be an Integer\n");
            ageField.requestFocus();
            }        
        }
    if (Integer.parseInt(ageBox) < 0 || Integer.parseInt(ageBox) > 116)
    {
      log.append("\nError reports\n==========\n");  
      log.append("Age must be in the range of 0-116\n");
      ageField.requestFocus();
    }
    if (!smokesField.getText().equalsIgnoreCase("Y") && !smokesField.getText().equalsIgnoreCase("N"))
    {
        log.append("\nError reports\n==========\n");
        log.append("Smoke input should be Y, y, N or n\n");
        smokesField.requestFocus();
    }
    if (!overweightField.getText().equalsIgnoreCase("Y") && !overweightField.getText().equalsIgnoreCase("N"))
    {
        log.append("\nError reports\n==========\n");
        log.append("Over Weight input should be Y, y, N or n\n");
        smokesField.requestFocus();
    }
    }

从你描述的情况来看,这条线很可能是

    if (Integer.parseInt(ageBox) < 0 || Integer.parseInt(ageBox) > 116)
{
...

抛出未处理的 NumberFormatException,因为您在 ageBox 中输入了一个字母。自从您的异常被 try/catch 处理程序捕获以来,您第一次获得 "Age must be an Integer" 的正确输出,但第二次出现时没有这样的处理。

要解决此问题,我只需将特定的 if 语句移动到 try 块中,如下所示:

    try
    {
        if (Integer.parseInt(ageBox) < 0 || Integer.parseInt(ageBox) > 116)
        {
            log.append("\nError reports\n==========\n");  
            log.append("Age must be in the range of 0-116\n");
            ageField.requestFocus();
        }
    }
    catch (NumberFormatException nfe)
    ...

这样,如果 ageBox 的条目无效,您仍然会得到 "Age must be an Integer" 的输出,其他一切都应该 运行 没问题。