Search code examples
javaaveragebluejgetmethod

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


Hi been stuck on figuring out the math coding on how to find the average horsepower of a specific year? If anyone can help me code this that would be great. I can also provide more info on the ArrayList or Class if you like, just comment.

Here is the method requirements:

public double getAverageHorsepowerOfYear(int modelYear)

  • returns the average horsepower of all Lamborghini objects that match the modelYear specified as the parameter.
  • 0.0 is returned if no Lamborghini cars match the model year specified
  • the value returned by this method MUST be a decimal number (10 / 3 = 3.3333334, not 3).

Here is my method:

public double getAverageHorsepowerOfYear(int modelYear)
{
    double avgHP = 0.0;


    for(Lamborghini l : inventory){
        if(l.getModelYear() == modelYear){
            avgHP = avgHP/l.getHorsepower();
            avgHP++;
        } 
    }
    return avgHP;
}

I have a feeling that this is incorrect so if anyone can help me with this that would be greatly appreciated. Thanks in advance.


Solution

  • You need to calculate total HP and divide that by number of cars.

    public double getAverageHorsepowerOfYear(int modelYear)
    {double TotalHP = 0.0;
    double avgHP = 0.0;
    int count = 0
    
    for(Lamborghini l : inventory){
        if(l.getModelYear() == modelYear){
            TotalHP = TotalHP + l.getHorsepower();
            count++;
        } 
    }
    avgHP = TotalHP/count;
    return avgHP;
    }