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
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 に答える
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 に答える