Search code examples
javaarraysinstance

How to find the average number in an array that has already been constructed


How could I write a method that returns the average weight of an array boxes. Assume that the array boxes has been constructed. Also can not assume that every element of the array has been constructed. If the array is empty the method should return 0.0. This is what I have at the moment but I am very lost.

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;
    }
}

Solution

  • Very easy if your using streams. average() returns an OptionalDouble so you can provide a default if the array is empty.

    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);
    

    Prints

    Avg weight = 20.0
    

    or more traditonally

    double sum = 0;
    int count = 0;
    for (Box b : boxes) {
       if (b != null) {
          sum += b.getWeight();
          count++;
        }
    }    
    System.out.println("Avg weight = " + (sum/count));
    

    Prints

    Avg weight = 20.0