0

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

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

2 回答 2

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);
   }
}
});
于 2013-03-15T09:23:59.110 回答
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
    }
}

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

于 2013-03-15T09:52:32.513 回答