这是我为您的问题建议的代码...
ArrayList<Integer> marks = new ArrayList<Integer>();
// Called when the user clicks a button
public void actionPerformed(ActionEvent e) {
Object clickedButton = e.getSource();
if(clickedButton == addButton) {
addButtonActionPerformed();
}
else if(clickedButton == sortButton) {
sortButtonActionPerformed();
}
else if(clickedButton == analyzeButton) {
analyzeButtonActionPerformed();
}
}
private void addButtonActionPerformed() {
Collections.addAll(marks, (Integer.parseInt(markInput.getText())));
StringBuilder text = new StringBuilder();
for (Integer mark: marks) {
text.append(mark.toString()).append('\n');
}
markdisplayTextArea.setText(text.toString());
}
private void sortButtonActionPerformed() {
Collections.sort(marks);
StringBuilder text = new StringBuilder();
for (Integer mark: marks) {
text.append(mark.toString()).append('\n');
}
markdisplayTextArea.setText(text.toString());
}
private void analyzeButtonActionPerformed() {
String output = "Class average:" + calculateAverage() + "\n" +
"Maximum mark:" + calculateMaximum() + "\n" +
"Minimum mark:" + calcualteMinimum() + "\n" +
"Range of marks:" + calculateRange();
analyzeTextArea.setText(output);
}
private int calculateAverage(){
// calculate and return the answer
}
private int calculateMaximum(){
// calculate and return the answer
int maximum = 0;
for (Integer currentMark: marks){
if (currentMark > maximum){
maximum = currentMark;
}
}
return maximum;
}
private int calcualteMinimum(){
// calculate and return the answer
}
private int calculateRange(){
// calculate and return the answer
}
现在,这些是我的主要更改,以及我做出这些更改的原因...
- 我添加了一个
actionPerformed()
方法。如果你还没有这个,它可以让你监听按钮点击。您需要myButton.addActionListener(this);
为每个按钮添加一行。您可能还需要将您的public class MyClass
行更改为 saypublic class MyClass implements ActionListener
并添加一行import java.awt.event.*
- 我更改了您的
analyzeButtonActionPerformed()
方法,以便它输出您请求的值。现在您需要calculate()
在最后实现这些方法 - 我已经为您完成了其中一个,以便为您提供总体思路。当您单击analyze
按钮时,它应该完成所有 4 次计算并将答案放入textarea
.
Why don't you have a bit of a look at my changes, and see whether you can see what they're supposed to be doing. Have a go at implementing some of the changes, and the calculate methods, and see if you can get it working. Don't just copy-paste my answer - make some changes bit-by-bit to see how it all works, and fix any compilation errors as they appear.