计算数组列表的平均值? [英] Calculating average of an array list?
本文介绍了计算数组列表的平均值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用以下代码来计算用户输入的一组值的平均值并将其显示在 jTextArea
中,但它无法正常工作.假设,用户输入 7、4 和 5,程序显示 1 作为平均值,而它应该显示 5.3
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();
}
代码有什么问题?
推荐答案
既然有了增强的 for 循环,为什么还要使用带有索引的笨拙的 for 循环?
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;
}
更新:正如其他几个人已经指出的那样,在 Java 8 及更高版本中使用 Streams 会变得更简单:
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)
}
这篇关于计算数组列表的平均值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文