Calculating average of an array list?
I'm trying to use the below code to calculate the average of a set of values that a user enters and display it in a jTextArea
but it does not work properly. Say, a user enters 7, 4, and 5, the program displays 1 as the average when it should display 5.3
ArrayList <Integer> marks = new ArrayList();
Collections.addAll(marks, (Integer.parseInt(markInput.getText())));
private void analyzeButtonActionPerformed(java.awt.event.ActionEvent evt) {
analyzeTextArea.setText("Class average:" + calculateAverage(marks));
}
private int calculateAverage(List <Integer> marks) {
int sum = 0;
for (int i=0; i< marks.size(); i++) {
sum += i;
}
return sum / marks.size();
}
What is wrong with the code?
With Java 8 it is a bit easier:
OptionalDouble average = marks
.stream()
.mapToDouble(a -> a)
.average();
Thus your average value is average.getAsDouble()
return average.isPresent() ? average.getAsDouble() : 0;
Why use a clumsy for loop with an index when you have the enhanced for loop?
private double calculateAverage(List <Integer> marks) {
Integer sum = 0;
if(!marks.isEmpty()) {
for (Integer mark : marks) {
sum += mark;
}
return sum.doubleValue() / marks.size();
}
return sum;
}
Update: As several others have already pointed out, this becomes much simpler using Streams with Java 8 and up:
private double calculateAverage(List <Integer> marks) {
return marks.stream()
.mapToDouble(d -> d)
.average()
.orElse(0.0)
}