慕尼黑的夜晚無(wú)繁華
2023-12-13 10:42:49
我從事 Java 應(yīng)用程序的工作。有一個(gè)Getter對(duì)應(yīng)一個(gè)整型字段(分?jǐn)?shù))。我的目標(biāo)是計(jì)算該字段的平均值。我決定創(chuàng)建一個(gè)數(shù)組,然后計(jì)算該數(shù)組的計(jì)數(shù)和總和。但我真的陷入了 Java 語(yǔ)法和“心態(tài)”之中。這是我的片段: 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貢獻(xiàn)1802條經(jīng)驗(yàn) 獲得超4個(gè)贊
為什么計(jì)算簡(jiǎn)單平均值太復(fù)雜?此外,我不明白為什么你需要數(shù)組。
int count = 0;
int sum = 0;
for (Person p : persons2) {
++count;
sum += p.getScoreTheo();
}
double average = sum / (double)count;

慕雪6442864
TA貢獻(xiàn)1812條經(jīng)驗(yàn) 獲得超5個(gè)贊
使用流:
public void setPersonData2(List<Person> persons2) {
double average = persons2.stream().mapToInt(p -> p.getScoreTheo()).average().getAsDouble();
//[...]
}
它引發(fā)NoSuchElementException一個(gè)空列表。

慕標(biāo)琳琳
TA貢獻(xiàn)1830條經(jīng)驗(yàn) 獲得超9個(gè)贊
Stream API 有一個(gè)內(nèi)置的平均函數(shù)。
double average = persons2.stream().collect(Collectors.averagingInt(person -> person.getScore()));
添加回答
舉報(bào)
0/150
提交
取消