Here is my suggested code for your problem...
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('
');
}
markdisplayTextArea.setText(text.toString());
}
private void sortButtonActionPerformed() {
Collections.sort(marks);
StringBuilder text = new StringBuilder();
for (Integer mark: marks) {
text.append(mark.toString()).append('
');
}
markdisplayTextArea.setText(text.toString());
}
private void analyzeButtonActionPerformed() {
String output = "Class average:" + calculateAverage() + "
" +
"Maximum mark:" + calculateMaximum() + "
" +
"Minimum mark:" + calcualteMinimum() + "
" +
"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
}
Now, these are my main changes, and why I made them...
- I added a
actionPerformed()
method. If you don't have this already, it allows you to listen for button clicks. You need to add a line myButton.addActionListener(this);
for each of your buttons. You'll probably also need to change your public class MyClass
line to say public class MyClass implements ActionListener
, and add a line import java.awt.event.*
- I changed your
analyzeButtonActionPerformed()
method so that it outputs the values you requested. Now you need to implement the calculate()
methods at the end - I have done one of them for you to give you the general idea. When you click the analyze
button, it should do all the 4 calculations and put the answers in the 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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…