首页 > 解决方案 > 如何在已经构建的数组中找到平均数

问题描述

我如何编写一个返回数组框的平均重量的方法。假设已经构建了数组框。也不能假设数组的每一个元素都已经构造好了。如果数组为空,则该方法应返回 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;
    }
}

标签: javaarraysinstance

解决方案


如果您使用流,则非常容易。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

推荐阅读