WordChecker is #3 from the from the 2024 AP Computer Science A Free Response problems.

https://apcentral.collegeboard.org/media/pdf/ap24-frq-comp-sci-a.pdf

Part (a) isWordChain method

public boolean isWordChain()
{
    for(int i = 1; i < wordList.size(); i++)
    {
        if(wordList.get(i).indexOf(
                wordList.get(i - 1)) == -1)
            return false;
    }
    
    return true;
}

Part (b) createList method

public ArrayList<String> createList(String target)
{
    ArrayList<String> result = new ArrayList<String>();
    
    for(String word : wordList)
    {
        if(word.indexOf(target) == 0)
            result.add(word.substring(target.length()));
    }
    
    return result;
}

Using indexOf to check if the word starts with target avoids the needs to check the lengths against each other. The String class also has a startsWith method; however, it is outside the AP Java Subset.

The single parameter substring method is explicitly allowed to accept a parameter 1 spot out of bounds. It returns the empty string.

See Strings on the AP CS A Exam for more details.

Java files with test code

ThreeTest.java includes JUnit 5 test code with the examples from the problem. See Running JUnit 5 tests.

WordChecker.java
ThreeTest.java

2024 AP CS Exam Free Response Solutions

Help & comments

Get help from AP CS Tutor Brandon Horn

See an error? Question? Please comment below.

Comment on WordChecker

2024-05-11 comment

Anonymous

For Part 3b, the “createList” method, in the explanation of your answer you seem to imply that we should not use the “startsWith” method because it is outside the AP Java Subset. However, since it is valid Java code, I don’t believe that actually excludes its use on the exam. For instance, do-while loops are not part of the AP Java Subset, yet they can be quite useful. I’m not advocating using obscure methods or confusing/tricky code, but for a fairly straightforward String method, why not use it?

Response

Yes, a solution that correctly used startsWith would receive full credit. My general recommendation is that students look for solutions within the subset first, since the problems were intended to be solved with subset methods. I did the same with this solution.