7.4.7. Free Response - StringFormatter A

The following is a free response question from 2016. It was question 4 part A on the exam. You can see all the free response questions from past exams at https://apstudents.collegeboard.org/courses/ap-computer-science-a/free-response-questions-by-year.

This question involves the process of taking a list of words, called wordList, and producing a formatted string of a specified length. The list wordList contains at least two words, consisting of letters only. When the formatted string is constructed, spaces are placed in the gaps between words so that as many spaces as possible are evenly distributed to each gap. The equal number of spaces inserted into each gap is referred to as the basic gap width. Any leftover spaces are inserted one at a time into the gaps from left to right until there are no more leftover spaces.

The following three examples illustrate these concepts. In each example, the list of words is to be placed into a formatted string of length 20.

../_images/2016FRQ4A1.png

The leftover spaces are inserted one at a time between the words from left to right until there are no more leftover spaces. In this example, the first two gaps get an extra space.

../_images/2016FRQ4A2.png

You will implement three static methods in a class named StringFormatter that is not shown.

7.4.7.1. Part A

(a) Write the StringFormatter method totalLetters, which returns the total number of letters in the words in its parameter wordList. For example, if the variableList<String> words is [“A”, “frog”, “is”],then the call StringFormatter.totalLetters(words) returns 7. You may assume that all words in wordList consist of one or more letters.

Complete method totalLetters below.

/** Returns the total number of letters in wordList.
*  Precondition: wordList contains at least two words, consisting of letters only.
*/
public static int totalLetters(List<String> wordList)

7.4.7.2. How to Solve Part A

Click to reveal the algorithm and multiple choice problems that may help you write your solution.

7.4.7.3. Put the Code in Order

7.4.7.4. Write the Code

Finish writing the totalLetters method below so that it returns the number of letters for all the strings in wordList. The main method below will test your code to check that you solved it correctly.

You have attempted of activities on this page