ACSA Exam Prep
← All free-response questions
Question 1 · Methods and Control Structures · 7 points

Step Challenge

A fitness app records a user's daily step counts. The StepChallenge class gives access to them.

public class StepChallenge
{
    /** Returns the number of steps taken on the given day.
     *  Precondition: 1 <= day <= the number of recorded days
     */
    private int getSteps(int day)
    { /* implementation not shown */ }

    /** Returns the first day on which the total number of steps
     *  from day 1 through that day is at least goal, or -1 if the
     *  total never reaches goal by day numDays.
     *  Precondition: numDays >= 1, goal > 0
     */
    public int dayGoalReached(int goal, int numDays)
    { /* to be implemented in part (a) */ }

    /** Returns the number of non-overlapping occurrences of
     *  target in text.
     *  Precondition: target.length() >= 1
     */
    public static int countWord(String text, String target)
    { /* to be implemented in part (b) */ }
}

Part (a)

4 points

Write dayGoalReached. Add up the steps day by day, starting with day 1. Return the first day on which the running total is at least goal. If the total is still below goal after day numDays, return -1.

Suppose getSteps returns these values:

Day12345
Steps30008000200090004000
CallReturnsWhy
dayGoalReached(10000, 5)23000 + 8000 = 11000
dayGoalReached(13000, 5)3The total reaches exactly 13000 on day 3
dayGoalReached(30000, 5)-1The 5-day total is only 26000
dayGoalReached(20000, 3)-1Only days 1–3 count
Tab inserts spaces. Drafts save as you type.

Part (b)

3 points

Write the static method countWord. It returns how many times target appears in text, without counting overlapping matches.

CallReturns
countWord("walk run walk walk", "walk")3
countWord("aaaa", "aa")2
countWord("steps", "run")0
Tab inserts spaces. Drafts save as you type.
Self-score
0 / 7