StepTracker is #2 from the from the 2019 AP Computer Science A Free Response problems.

https://apcentral.collegeboard.org/pdf/ap19-frq-computer-science-a.pdf?course=ap-computer-science-a

StepTracker class

public class StepTracker
{
    private final int minStepsActive;
    private int activeDays;
    private int days;
    private int totalSteps;

    public StepTracker(int minStepsActive)
    {
        this.minStepsActive = minStepsActive;
        activeDays = 0;
        days = 0;
        totalSteps = 0;
    }

    public void addDailySteps(int steps)
    {
        if(steps >= minStepsActive)
            activeDays++;

        days++;
        totalSteps += steps;
    }

    public int activeDays()
    {
        return activeDays;
    }

    public double averageSteps()
    {
        if(days == 0)
            return 0;

        return totalSteps / (double) days;
    }
}

It is common for students to unnecessarily store an Arraylist. This makes the code inside the methods unnecessarily complex. See Class writing order for a technique to respond to AP CS FR that request an entire class. See Class writing exercise for a similar problem.

Storing averageSteps as an instance variable is a common mistake. Do not store instance variables with values that can be calculated from the values of other instance variables. See Duplicate data as instance variables for additional discussion. In the absence of an effect on behavior, the scoring guide does not penalize this mistake.

StepTracker class (alternate solution)

I’ve received many questions about whether this problem can/should be done using an ArrayList. There is no benefit to using an ArrayList vs storing only the data you actually need to implement the methods. That said, a correct solution using an ArrayList would receive full credit.

public class StepTracker
{
    private final int minStepsActive;
    private ArrayList<Integer> stepsPerDay;

    public StepTracker(int minStepsActive)
    {
        this.minStepsActive = minStepsActive;
        stepsPerDay = new ArrayList<Integer>();
    }

    public void addDailySteps(int steps)
    {
        stepsPerDay.add(steps);
    }

    public int activeDays()
    {
        int activeDays = 0;

        for(Integer steps : stepsPerDay)
            if(steps >= minStepsActive)
                activeDays++;

        return activeDays;
    }

    public double averageSteps()
    {
        if(stepsPerDay.size() == 0)
            return 0;

        int totalSteps = 0;

        for(Integer steps : stepsPerDay)
            totalSteps += steps;

        return (double) totalSteps / stepsPerDay.size();
    }
}

Again, I don’t recommend this solution. I’ve added it here in response to the many questions I’ve received about it.

2019 AP CS Exam Free Response Solutions

Additional classes & objects resources

Help & comments

Get help from AP CS Tutor Brandon Horn

Comment on StepTracker