我在开发 Java 应用程序。
有一个Getter对应一个整型字段(score)。
我的目标是计算该字段的平均值。我决定创建一个数组,然后计算该数组的计数和总和。
但我真的被 Java 语法和“心态”所困。
这是我的片段:
public void setPersonData2(List<Person> persons2) {
// Try to make a count of the array
int[] scoreCounter = new int[100]; // 100 is by default since we don't know the number of values
for (Person p : persons2) {
int score = p.getScoreTheo(); // Getter
Arrays.fill(scoreCounter, score);
// Try to delete all values equal to zero
int[] scoreCounter2 = IntStream.of(scoreCounter).filter(i -> i != 0).toArray();
// Calculate count
int test = scoreCounter2.length;
System.out.println(test);
}
}
你能帮帮我吗?
最佳答案
为什么计算简单平均值太复杂了?此外,我不明白你为什么需要数组。
int count = 0;
int sum = 0;
for (Person p : persons2) {
++count;
sum += p.getScoreTheo();
}
double average = sum / (double)count;
关于Java - 尝试计算来自 Getter 的值的平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58543814/