java - 如何在已经构建的数组中找到平均数
问题描述
我如何编写一个返回数组框的平均重量的方法。假设已经构建了数组框。也不能假设数组的每一个元素都已经构造好了。如果数组为空,则该方法应返回 0.0。这就是我现在所拥有的,但我很迷茫。
public class Question03 {
//The array of boxes to be used by the method "getAverageWeight()"
//This property is public for testing purposes
public Box[] boxes;
public double getAverageWeight()
{
int h = boxes.length;
double avg = 0.0;
for(int i = 0;i<boxes.length;i++)
{
if(boxes[i] == null)
{
h--;
}
}
return avg;
}
}
解决方案
如果您使用流,则非常容易。average()
返回一个OptionalDouble
,因此如果数组为空,您可以提供默认值。
Box[] boxes =
{ new Box(10), new Box(20), null, null, new Box(30) };
double avg = Arrays.stream(boxes).filter(obj -> obj != null)
.mapToDouble(Box::getWeight).average().orElse(0.);
System.out.println("Avg weight = " + avg);
印刷
Avg weight = 20.0
或更传统的
double sum = 0;
int count = 0;
for (Box b : boxes) {
if (b != null) {
sum += b.getWeight();
count++;
}
}
System.out.println("Avg weight = " + (sum/count));
印刷
Avg weight = 20.0
推荐阅读
- mongodb - 同一字段在 MongoDB 查询中使用了两次
- wordpress - 使用 WordPress REST API 将用户设置为相当于“站点无角色”的角色
- c - 如何使用排序索引对c中结构数组中的整数进行排序?
- ios - 如何使用 Swift 为横向模式创建当前底部视图的正确位置?
- json - Dart HTTP POST 与 Map
作为身体 - node.js - 这个快速应用程序中的回调来自哪里?
- google-bigquery - 根据先前的查询从表中选择列
- wordpress - 重置帐户后,woocommerce 在同一页面中重定向
- c - 从输入文件中读取并将单词存储到数组中
- java - 如何解决在 Android Studio 2.2 上使用记录为 @since 1.8+ 错误的 API 的问题?