JTextField数据验证

时间:2017-03-01 14:21:50

标签: java string validation int jtextfield

Java新手,所以非常感谢任何帮助。在JTextField中进行数据验证时遇到一个小问题。 要求用户输入他们的年龄,他们是否吸烟,以及他们是否超重。 对吸烟和体重的验证工作正常,我设定的年龄限制也是如此。

但是,如果我在ageField JTextField中输入一个字母,它似乎卡住了,并且不会打印其他验证错误。 (例如它将正确打印"年龄必须是整数"但是如果我也在smokesField中键入' h"烟雾输入应该是Y,y,N或n& #34;不会被打印。)

对不起,这是一个冗长而臃肿的解释!

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

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

1 个答案:

答案 0 :(得分:0)

根据您描述的情况,很可能是

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

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

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

    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必须是整数”的输出,其他一切都应该正常运行。