StringFormatter is #4 from the from the 2016 AP Computer Science A Free Response problems.

https://secure-media.collegeboard.org/digitalServices/pdf/ap/ap16_frq_computer_science_a.pdf

Part (a) totalLetters method

public static int totalLetters(List<String> wordList)
{
    int letters = 0;

    for(String word : wordList)
        letters += word.length();

    return letters;
}

Part (b) basicGapWidth method

public static int basicGapWidth(List<String> wordList, int formattedLen)
{
    int gaps = wordList.size() - 1;
    int spaces = formattedLen - totalLetters(wordList);
    return spaces / gaps;
}

I checked my logic for this on all 3 of the examples before I wrote the code. The examples often include special cases and are invaluable for checking logic.

Part (c) format method

public static String format(List<String> wordList, int formattedLen)
{
    int width = basicGapWidth(wordList, formattedLen);
    int leftoverRemaining = leftoverSpaces(wordList, formattedLen);

    String formatted = "";
    for(int i = 0; i < wordList.size() - 1; i++)
    {
        formatted += wordList.get(i);

        for(int s = 1; s <= width; s++)
            formatted += " ";

        if(leftoverRemaining > 0)
        {
            formatted += " ";
            leftoverRemaining--;
        }
    }

    formatted += wordList.get(wordList.size() - 1);

    return formatted;
}

The loop to append the basic number of spaces could be moved outside the loop through wordList. (A variable would be used to store the correct number of spaces, which could then be appended between words.) I left my original solution since it made sense to me when I wrote it.

See Strings on the AP CS A Exam for an explanation of concatenating String objects on the AP CS A Exam.

This problem requires careful allocation of spaces and careful consideration of the last word.

When I first wrote this, I got sloppy and wrote a loop without thinking about the bounds. Whenever you do this, you run the risk of being off by 1. (The solution above is correct.)

2016 AP CS Exam Free Response Solutions

Help & comments

Get help from AP CS Tutor Brandon Horn

Comment on StringFormatter