【问题标题】:JTextField Data ValidationJTextField 数据验证
【发布时间】:2017-07-20 22:12:26
【问题描述】:

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();
    }
    }

【问题讨论】:

  • 第二个Integer.parseInt(ageBox) 会抛出异常

标签: java string validation int jtextfield


【解决方案1】:

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

    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”的输出,并且其他一切都应该运行正常。

【讨论】:

  • 感谢您的快速回复。尝试了您的建议,现在效果很好。
  • @RiceCrispy 没问题,很高兴你发现它有帮助!
猜你喜欢
  • 2012-12-31
  • 1970-01-01
  • 2020-11-19
  • 2013-04-29
  • 1970-01-01
  • 2014-04-12
  • 2013-10-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多