我有一组数字,命名为age[],我想计算age[]中所有元素的平均值,而不单独计算总和,不是像这样:
int avg2 = (age[0] + age[1] + age[2] + age[3] + age[4] + age[5]) / age.length;
这实在是太长了,想象一下,如果一个有100个元素,那就太难了。
int age[] = { 20, 17, 19, 22, 18, 18 };
String[] names = { "Ahmed", "Sam", "Mandi", "Amine", "John", "Rayan" };
for (int i = 0; i <= 5; i++) {
if (age[i] >= 20) {
System.out.println(names[i] + " is " + age[i] + " years old. And he's from Mars!");
}
if (age[i] < 20) {
System.out.println(names[i] + " is " + age[i] + " years old. He is from Wakanda!");
}
}
int j = 0;
int avg = (age[j] + age[j++]) / age.length;
System.out.println("Their average age is :" + avg + " years.");
int avg2 = (age[0] + age[1] + age[2] + age[3] + age[4] + age[5]) / age.length;
System.out.println("Their correct average age is :" + avg2 + " years.");
我已经查过了,但是没有找到捷径。如果可能的话,请帮我解决这个问题。谢谢。
3条答案
按热度按时间busg9geu1#
可以在迭代数组时对
age
的值求和。不要在for
循环中硬编码长度。使用一个else
而不是两个if
。类似于z2acfund2#
最简单的方法之一是使用Java Streams API。
4xrmg8kj3#
这里有一种稍微不同的做法。
IntStream
流式传输数组索引。map
打印每个个体的年龄印刷品