我的文本字段有验证表格

时间:2013-03-15 09:14:39

标签: java swing numbers jtextfield parseint

代码不检查文本字段是否为空 //按钮计算cat1,cat2,考试的输入,并给出平均值和总数

btnCompute_1 = new JButton("COMPUTE");
btnCompute_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
    String a=cat1.getText().toString();
    String b=textcat_2.getText().toString();
    String c=textExam.getText().toString();
    //String[] results=new String[2];
    int catMark1,catMark2,Average,Exam,Total;
    catMark1=Integer.parseInt(a);
    catMark2=Integer.parseInt(b);
    Exam=Integer.parseInt(c);
    Average=((catMark1+catMark2)/2);
    Total=(Average+Exam);
    System.out.println("aver:" +Average +" tot:" +Total +" cat1:" +catMark1+" cat2" +catMark2);

    textAverage.setText("Average:"  +String.format("%d",Average));
    textTotal.setText("Total:"  +String.format("%d",Total));
    if(cat1.getText().equals(null)){
       JOptionPane.showMessageDialog(null,"Cat 1 marks are missing", "Error", 
       JOptionPane.ERROR_MESSAGE);
       }
     }
});

2 个答案:

答案 0 :(得分:0)

btnCompute_1 = new JButton("COMPUTE");
btnCompute_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
    String a=cat1.getText().toString();
    String b=textcat_2.getText().toString();
    String c=textExam.getText().toString();
   //String[] results=new String[2];
   int catMark1,catMark2,Average,Exam,Total;
   catMark1=Integer.parseInt(a);
   catMark2=Integer.parseInt(b);
   Exam=Integer.parseInt(c);
   Average=((catMark1+catMark2)/2);
   Total=(Average+Exam);
   System.out.println("aver:" +Average +" tot:" +Total +" cat1:" +catMark1+" cat2" +catMark2);

   textAverage.setText("Average:"  +String.format("%d",Average));
   textTotal.setText("Total:"  +String.format("%d",Total));
   if(cat1.getText != null && cat1.getText.length() > 0){ //check this 
        JOptionPane.showMessageDialog(null,"Cat 1 marks are missing", "Error",        JOptionPane.ERROR_MESSAGE);
   }
}
});

答案 1 :(得分:0)

String a=cat1.getText(); // getText() is often a String; no need to toString it

if(a == null || a.length() == 0) {
    // error
}
else {
    try {
        catMark1=Integer.parseInt(a);
    }
    catch(NumberFormatException nfe) {
    {
        // could not parse
    }
}

您可以清理订单(这仅用于说明目的)