?

AP® Computer Science A

Free Version

Upgrade subject to access all content

Moderate

ArrayList of Baby Objects: FInding Average Weight of Babies

APCSA-8ETNX1

Consider the following class.

public class Baby 
{
    private String firstName;
    private String lastName;
    private double weight;
    private String gender;   // M or F

    public double getWeight()
    {
        // returns the weight of the baby
    }

    public String getGender()
    {
        // returns the gender of the baby
    }

    // other data and methods not shown
}

Which of the following methods from another class will return the average weight of a selected gender of babies in the array list? (The method should return zero if there are no babies of that gender in the array list.)

A
public static double getAvgBabyWeight(ArrayList<Baby> babies, String gender)
{
    double count=0, totWeight=0;
    for (int i=0; i<babies.size(); i++)
    {
        if (babies.getGender().equals(gender))
        {
            count++;
            totWeight+=babies.getWeight();
        }
    }
    if (count==0)
        return 0;
    return totWeight/count;
}
B
public static double getAvgBabyWeight(ArrayList<Baby> babies, String gender)
{
    double count=0, totWeight=0;
    for (String baby : babies)
    {
        if (baby.getGender().equals(gender))
        {
            count++;
            totWeight+=baby.getWeight();
        }
    }
    return totWeight/count;
}
C
public static double getAvgBabyWeight(ArrayList<Baby> babies, String gender)
{
    double count=0, totWeight=0;
    for (Baby baby : babies)
    {
        if (baby.gender.equals(gender))
        {
            count++;
            totWeight+=baby.weight;
        }
    }
    return totWeight/count;
}
D
public static double getAvgBabyWeight(ArrayList<Baby> babies, String gender)
{
    double count=0, totWeight=0;
    for (int i=0; i<babies.size(); i++)
    {
        if (babies.get(i).getGender().equals(gender))
        {
            count++;
            totWeight+=babies.get(i).getWeight();
        }
    }
    if (count==0)
        return 0;
    return totWeight/count;
}
E
public static double getAvgBabyWeight(ArrayList<Baby> babies, String gender)
{
    double count=0, totWeight=0;
    for (int i=0; i<babies.size(); i++)
    {
        if (babies.get(i).getGender().equals(gender))
        {
            count++;
            totWeight+=babies.get(i).getWeight();
        }
    }
    if (count==0)
        System.out.println(0);
    System.out.println(totWeight/count);
}