为了账号安全,请及时绑定邮箱和手机立即绑定

Java - 尝试计算来自 Getter 的值的平均值

Java - 尝试计算来自 Getter 的值的平均值

慕尼黑的夜晚无繁华 2023-12-13 10:42:49
我从事 Java 应用程序的工作。有一个Getter对应一个整型字段(分数)。我的目标是计算该字段的平均值。我决定创建一个数组,然后计算该数组的计数和总和。但我真的陷入了 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);        } }你可以帮帮我吗 ?
查看完整描述

3 回答

?
慕虎7371278

TA贡献1802条经验 获得超4个赞

为什么计算简单平均值太复杂?此外,我不明白为什么你需要数组。


int count = 0;

int sum = 0;

for (Person p : persons2) {

   ++count;

   sum += p.getScoreTheo();

}


double average = sum / (double)count;


查看完整回答
反对 回复 2023-12-13
?
慕雪6442864

TA贡献1812条经验 获得超5个赞

使用流:


public void setPersonData2(List<Person> persons2) {

    double average = persons2.stream().mapToInt(p -> p.getScoreTheo()).average().getAsDouble();

    //[...]

}

它引发NoSuchElementException一个空列表。


查看完整回答
反对 回复 2023-12-13
?
慕标琳琳

TA贡献1830条经验 获得超9个赞

Stream API 有一个内置的平均函数。

double average = persons2.stream().collect(Collectors.averagingInt(person -> person.getScore()));


查看完整回答
反对 回复 2023-12-13
  • 3 回答
  • 0 关注
  • 81 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信