- StringFormatter.java
- StringFormatterTester.java
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.
Part A
Write the StringFormatter
method totalLetters
, which returns the total number of letters in the words in its parameter wordList
. For example, if the variable ArrayList<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.
Part B
Write the StringFormatter
method basicGapWidth
, which returns the basic gap width as defined earlier.
Part C
Write the StringFormatter
method format
, which returns the formatted string as defined earlier. The StringFormatter
class also contains a method called leftoverSpaces
, which has already been implemented. This method returns the number of leftover spaces as defined earlier and is shown below.
/** Returns the number of leftover spaces when wordList is used to produce
* a formatted string of formattedLen characters.
* Precondition: wordList contains at least two words, consisting of letters only.
* formattedLen is large enough for all the words and gaps. */
public static int leftoverSpaces(List<String> wordList, int formattedLen)
{ /* implementation not shown */ }
Assume that basicGapWidth
works as specified, regardless of what you wrote in part (b). You must use basicGapWidth
and leftoverSpaces
appropriately to receive full credit.
Upload an image
Upload from your computer
Or paste a link here
Slides and Notes
No slides available for this video
About
Java (main)
Java Version 1.8.0_222