Account is #1 from the from the 2026 AP Computer Science A Free Response problems.

https://apcentral.collegeboard.org/media/pdf/ap26-frq-computer-science-a.pdf

Part (a) Account constructor

public Account(String requestedName)
{
    if(isAvailable(requestedName))
    {
        username = requestedName;
    }
    else
    {
        int n = 1;

        while( ! isAvailable(requestedName + n) )
            n++;

        username = requestedName + n;
    }
}

Part (b) getShortenedName method

public String getShortenedName()
{
    String shortened = username;

    int i = 1;
    while(i < shortened.length())
    {
        if(shortened.substring(i, i + 1).equals("-"))
        {
            shortened = shortened.substring(0, i - 1) +
                    shortened.substring(i + 1);

            i--;
        }
        else
        {
            i++;
        }
    }

    return shortened;
}

Similar to scrambleWord from 2014 A FR #1, pretending the String object is mutable (by constructing a new String object) makes this problem easier.

Given the preconditions, neither substring call will cause a StringIndexOutOfBoundsException. See Strings on the AP CS A Exam for more details.

Part (b) getShortenedName method (alternate solution 1)

public String getShortenedName()
{
    String shortened = "";

    int i = username.length() - 1;

    while(i >= 0)
    {
        if(username.substring(i, i + 1).equals("-"))
        {
            i -= 2;
        }
        else
        {
            shortened = username.substring(i, i + 1) + shortened;
            i--;
        }
    }

    return shortened;
}

Traversing username backwards avoids the need to check two characters to determine if one character should be added to shortened.

Part (b) getShortenedName method (alternate solution 2)

public String getShortenedName()
{
    String shortened = "";

    for(int i = 0; i < username.length(); i++)
    {
        if( ! username.substring(i, i + 1).equals("-") &&
                (i == username.length() - 1 ||
                ! username.substring(i + 1, i + 2).equals("-")))
        {
            shortened += username.substring(i, i + 1);
        }
    }

    return shortened;
}

Traversing username from left to right requires an annoyingly complex condition to determine whether to add the character at i to shortened.

Java files with test code

Account.java
OneTest.java

See Running JUnit 5 tests.

2026 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 Account