请问我想知道如何让jtxtScore [6]显示字母等级,它会计算平均等级,但我也希望它能显示字母等级.`
public class ScoreGUI extends JFrame implements ActionListener{
final int SIZE=6;
JButton jbtnCalculate = new JButton ("Calculate");
JTextField [] jtxtScore = new JTextField[SIZE];
JTextField [] jtxtWeight = new JTextField[SIZE];
JLabel [] jlblModuleName = new JLabel[SIZE];
JPanel scorePanel = new JPanel();
JPanel buttonPanel = new JPanel();
double []scores = new double[SIZE];
double []weights = new double[SIZE];
public ScoreGUI(){
jlblModuleName [0]= new JLabel("Assignments");
jlblModuleName [1] = new JLabel("Mid term");
jlblModuleName [2]= new JLabel("final exam");
jlblModuleName [3]= new JLabel("Final Project");
jlblModuleName [4]= new JLabel("grade average");
jlblModuleName [5]= new JLabel("letter grade");
scorePanel.setBackground(Color.gray);
scorePanel.setLayout(new GridLayout(7,3,5,9));
for(int i=0; i<SIZE;i++){
scorePanel.add(jlblModuleName[i]);
jtxtScore[i] = new JTextField(8);
scorePanel.add(jtxtScore[i]);
jtxtWeight[i] = new JTextField(8);
scorePanel.add(jtxtWeight[i]);
//add(jtxtWeight[i]);
}
buttonPanel.setBackground(Color.CYAN);
jbtnCalculate.addActionListener(this);
buttonPanel.add(jbtnCalculate);
add(scorePanel, BorderLayout.CENTER);
add(buttonPanel, BorderLayout.SOUTH);
setVisible(true);
setSize(500,500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
}
public double calculateScore(double[]score, double[]weight){
double grade=0.0;
grade = (score[0]*weight[0]+score[1]*weight[1]+score[2]*weight[2]+score[3]*weight[3]);
return grade;
}
public char calculateLetter(char grade){
char letter='N';
if(grade>=90)
letter = 'A';
else if(grade>=80)
letter = 'B';
else if(grade>=70)
letter = 'C';
else if(grade>=60)
letter = 'D';
else if(grade<50)
letter = 'F';
return letter;
}
public void actionPerformed(ActionEvent e){
for(int i=0;i<4;i++){
scores[i] = Double.parseDouble(jtxtScore[i].getText());
weights[i] = Double.parseDouble(jtxtWeight[i].getText());
}
jtxtScore[4].setText(calculateScore(scores,weights)+"");
jtxtScore[5].setText(calculateLetter) // what do I have to do here?
}
}
`
答案 0 :(得分:1)
这些行:
jtxtScore[4].setText(calculateScore(scores,weights)+"");
jtxtScore[5].setText(calculateLetter) // what do I have to do here?
您应该计算分数并首先将返回的值放入双变量中。
即,
double score = calculateScore(scores,weights);
jtxtScore[4].setText(score + "");
然后,您应该使用score
方法中的calculateLetter
值来获取所需的字符。请注意,您可能希望更改calculateLetter
以获取double参数而不是char,因为char参数没有意义。
[编辑] 作为旁注,虽然我鼓掌使用数组,因为它们极大地简化了代码,但我认为你不应该将它们用于最后两个JTextFields,因为这些JTextField并不都拥有与其他类型相同的信息类型。在你的代码中,我认为你在命名这些JTextFields,scoreField和letterGradeField或类似东西方面要好得多。这样做可以使您的代码自我评论,让其他人更容易理解您的代码。
另外,我在这里使用for循环:
grade = (score[0]*weight[0]+score[1]*weight[1]+score[2]*weight[2]+score[3]*weight[3]);
而不是硬编码一切。如果需要,这将允许您稍后使用不同数量的分数。