Nobby Nobby - 2 months ago 18
Java Question

Java swing - list.add issues

I'm creating a GUI for use in a judged sporting event. There are 6 judges and they each input their score into the GUI. They then hit calculate, and the program is meant to sort the numbers from low to high and then take the numbers from position 1 through 4 and give an average.

I have written the code for input via console and that works, but when I try my Gui the 'list.add' doesn't work. I don't know if I am meant to use something else.

btnCalculate = new JButton("Calculate");
btnCalculate.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
inGui = new Scanner (System.in);
double firstRun = getAverageOfRun(1);
double secondRun = getAverageOfRun(2);
double best;

if (firstRun > secondRun) {
best = firstRun;
} else {
best = secondRun;
}
textFieldRun1Score.setText(Double.toString(best));
}
private double getAverageOfRun (int runNumber) {
double total, avg;
int num1, num2, num3, num4, num5, num6;
List<Integer> list = new ArrayList<Integer>();

num1 = Integer.parseInt(textFieldRun1Score1.getText());

System.out.print(""+runNumber +": ");
list.add(textFieldRun1Score1.getText());
list.add(textFieldRun1Score2.getText());
list.add(textFieldRun1Score3.getText());
list.add(textFieldRun1Score4.getText());
list.add(textFieldRun1Score5.getText());
list.add(textFieldRun1Score6.getText());

Collections.sort(list);

total = list.get(1) + list.get(2) + list.get(3) + list.get(4);

avg = total / 4;

textFieldBestScore.setText(Double.toString(avg));
return avg;

}

Answer

This code won't compile for a simple reason: type mismatch. Just split this line:

list.add(textFieldRun1Score1.getText());

up: list.add(...) expects an int as parameter (since it's templatetype is Integer), textFieldRun1Score1.getText() returns a String. Thus you'll have to convert from String to int first. Most common way to solve this is int value = Integer.parseInt(string);