我從事 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;

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

慕標琳琳
TA貢獻1830條經驗 獲得超9個贊
Stream API 有一個內置的平均函數。
double average = persons2.stream().collect(Collectors.averagingInt(person -> person.getScore()));
添加回答
舉報
0/150
提交
取消