2017-03-01 72 views
0

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

但是,如果我在ageField JTextField中输入一个字母,它似乎会卡住并且不会打印其他验证错误。 (例如,它会正确打印“年龄必须是整数”,但是如果我也在smokesField中键入“h”,“烟雾输入应该是Y,y,N或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(); 
    } 
    } 
+0

第二个'Integer.parseInt(ageBox)'会抛出异常 – Jerry06

回答

0

从你描述的情况,很可能是线路

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

抛出未处理NumberFormatException的,因为你已经在ageBox中输入了一封信。您的try/catch处理函数捕获异常后第一次得到“Age必须是整数”的正确输出,但第二次出现没有这种处理。

为了解决这个问题,我想简单地移动特定的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有一个无效的条目,其他一切都应该运行良好。

+0

Thankyou的快速回复。 试过你的建议,现在完美地工作。 – RiceCrispy

+0

@RiceCrispy没问题,我很高兴你发现它有帮助! –