2024 AP CSA FRQ 3 Solution – WordChecker ArrayList & Strings
2024 AP CSA FRQ 3 – WordChecker (Solution)
This solution shows how to implement isWordChain and createList in the WordChecker class using ArrayList<String> and String methods like contains, startsWith, and substring.
Part (a) – isWordChain
Goal: Return true if every word (except the first) contains the previous word as a substring; otherwise return false.
We loop from index 1 to the end, and for each index
i check whether wordList.get(i) contains wordList.get(i - 1).public boolean isWordChain()
{
// Precondition: wordList has at least two elements
for (int i = 1; i < wordList.size(); i++)
{
String prev = wordList.get(i - 1);
String current = wordList.get(i);
if (!current.contains(prev))
{
return false;
}
}
return true;
}
Why this earns full credit:
- Uses a single pass through the list, checking each adjacent pair.
- Uses
containsin the correct direction (current.contains(previous)). - Leaves
wordListunchanged (only reads values).
Part (b) – createList
Goal: Build and return a new ArrayList<String> containing pieces of the words in wordList that start with target, with that starting occurrence removed.
We must:
- Scan every word in
wordListin order. - If a word starts with
target, remove that prefix usingsubstring. - Add the “stripped” string to the result list in the same order as in
wordList. - Leave
wordListitself unchanged.
public ArrayList<String> createList(String target)
{
ArrayList<String> result = new ArrayList<String>();
for (int i = 0; i < wordList.size(); i++)
{
String word = wordList.get(i);
if (word.startsWith(target))
{
// Remove the starting occurrence of target
String stripped = word.substring(target.length());
result.add(stripped);
}
}
return result;
}
Why this matches the examples:
- When a word begins with
target, e.g."catch"with"cat", removing the prefix produces"ch". - When the word equals
targetexactly, the substring is the empty string"", which still gets added. - If no words start with
target, the returned list is empty. - Order of elements in the result matches the original order of
wordList.
Common mistakes: using
contains instead of startsWith, modifying wordList directly, or using an incorrect substring index when removing the prefix.