How to return the average horsepower of all objects that match a specified year? java

You calculation for the average is all wrong. You have to find the sum of the horsepower, then divide it by the total number of cars matching your criterion. What you do instead is… divide the running average by the new HP and then add one to it?

Looks like an assignments, so here’s some pseudocode:

public double getAverageHorsepowerOfYear(int modelYear) {
    sum = 0.0
    count = 0
    for each car:
        if criterion matches:
            add HP to sum
            increment count
    return sum / count
}

Leave a Comment