Part 1 · The core language

ACheckpoint project A

This is the end of Part 1, and it is a project, not a lesson. You will build one console program, TextTool, that reads text from the command line and reports on it: its words, how many characters and letters it has, how often each letter and each word occurs. You build it in six milestones. Each adds a piece of the program, most of them one command and one or two methods, and later milestones reuse the methods of earlier ones. It asks for almost nothing you have not met. What is new is the size: a good many methods that have to agree with each other.

By the end you will have

  • written a command-line program that chooses what to do from its first argument, with an arrow switch, and explains itself when it is misused
  • split text into words by scanning it one character at a time, and then reused that one method in the commands that follow
  • counted characters, letters and digits, and printed an aligned summary with printf
  • counted letters with char arithmetic into an int[], and drawn a bar chart from the counts
  • written methods that take lists and must leave them unchanged, and a hand-written loop that keeps two lists in step
  • designed before coding, traced a method by hand, and kept a log of your tests

The finished program at work

Here is the whole program running. These sessions come from a reference solution, whose code you do not see: writing it is the exercise. Every command takes the command name first, then the text. Start with what it does when used wrongly.

Terminal
> javac TextTool.java
> java TextTool
Usage: java TextTool <command> <text>
Commands: words, count, freq, tally, reverse, longest, ranked
> java TextTool words
Usage: java TextTool <command> <text>
Commands: words, count, freq, tally, reverse, longest, ranked
> java TextTool dance now
Unknown command: dance

With no arguments, or with a command and no text, it prints a two-line usage message. With a command it does not know, it names the command. The words command splits the text into words:

Terminal
> javac TextTool.java
> java TextTool words "Meet me at 9:30, by the old clock-tower."
1. Meet
2. me
3. at
4. 9
5. 30
6. by
7. the
8. old
9. clock
10. tower
Words: 10
> java TextTool words quotes are optional here
1. quotes
2. are
3. optional
4. here
Words: 4

The colon in 9:30 and the hyphen in clock-tower are neither letters nor digits, so they separate words: 9 and 30 are two words, and so are clock and tower. That makes ten words. In the second run there are no quotes. The four arguments after the command are joined with single spaces into one text, so the quotes are optional.

The count command summarises the text:

Terminal
> javac TextTool.java
> java TextTool count "Room 101 is on the 3rd floor, not the 2nd."
Characters:     42
Letters:        26
Digits:          5
Words:          10

The freq command prints one line for each letter that occurs, in alphabetical order, with its count and a bar of stars. Capital and small letters count together.

Terminal
> javac TextTool.java
> java TextTool freq "Mississippi river"
e   1 *
i   5 *****
m   1 *
p   2 **
r   2 **
s   4 ****
v   1 *

The tally command lists each distinct word once, in lower case, in the order it first appears, with the number of times it occurs. It and it are the same word:

Terminal
> javac TextTool.java
> java TextTool tally "It was the best of times, it was the worst of times"
it           2
was          2
the          2
best         1
of           2
times        2
worst        1

The last three commands are the stretch milestone. reverse prints the words backwards on one line. longest prints the longest word, and when two words tie, the earlier one wins: clock and tower both have five letters, and clock comes first. ranked prints the tally with the most frequent words first. Words with equal counts stay in the order of their first appearance, so best is now below of and times.

Terminal
> javac TextTool.java
> java TextTool reverse "Meet me at 9:30, by the old clock-tower."
tower clock old the by 30 9 at me Meet
> java TextTool longest "Meet me at 9:30, by the old clock-tower."
Longest word: clock, length 5
> java TextTool ranked "It was the best of times, it was the worst of times"
it           2
was          2
the          2
of           2
times        2
best         1
worst        1

The rules

The project is a test of how well you can combine what you already know, so it comes with rules. Some say what to build and some say what to leave out.

Here is the map from the milestones to the lessons they draw on. When you are stuck, go back to the section named for the idea you need.

MilestoneBuilds on
1 · SkeletonLesson 7: command-line arguments and the usage message. Lesson 3: the arrow switch on a String. Lesson 4: the for loop. Lesson 6: StringBuilder.
2 · wordsLesson 6: looping over a string and the Character methods, and StringBuilder. Lesson 7: ArrayList. Lesson 4: building up a result across passes.
3 · countLesson 4: the counting pattern. Lesson 6: printf. Lesson 5: methods that do one job, here by calling the method from milestone 2.
4 · freqLesson 6: arithmetic on letters (and lesson 2, char is a number underneath). Lesson 7: arrays, their default values, and returning an array. Lesson 6: repeat for the bars.
5 · tallyLesson 7: the ArrayList methods (contains and get especially), and what happens when a method receives a list (Lists are objects too). Lesson 6: equalsIgnoreCase and toLowerCase.
6 · stretchLesson 7: lists of Integer and the traps in them, and changing a list safely. Lesson 4: largest so far, and nested loops.

Several methods resemble exercises you have already done. If you wrote those, you may adapt your own earlier solutions. Reuse is part of the point. Read the differences first.

How to work on a project this size

A program with many methods fails in new ways. A mistake in the first method shows itself as a strange result in the fifth. These habits keep that manageable.

  1. One milestone at a time. Finish a milestone, including its edge cases, before you start the next. Each milestone check needs only that milestone's methods and the ones before it.
  2. Write the header and a contract first. Before you write a method, write its header and one sentence saying what it returns and what it assumes: returns the number of letters in text. A contract, in this sense, is that sentence: what the caller may rely on. The DESIGN.md file has a table for them. If you cannot write the sentence, you are not ready to write the method.
  3. Compile after every few lines. Lesson 1 taught you to fix the first error and compile again. That is easy with three new lines and hard with sixty.
  4. Test each method alone before you build on it. Put a temporary line at the top of main that calls the new method with a text you chose, and prints the result. Printing a list prints its contents in square brackets (lesson 7), so a call such as the one below shows you the whole answer. Delete the line once the method works, and keep a note of what you tried.
public static void main(String[] args) {
    System.out.println(splitWords("..up-to 9"));   // temporary test: delete when it works
    // ... the real main continues here
}
  1. Keep a test log. A table with the input, what you expected, what you got and what you changed. Write the expectation before you run, as you did for the prediction logs in earlier lessons. A log shows you which kinds of mistake you keep making, and it is part of what is reviewed.
  2. When something is wrong, make the input smaller. If words gives a wrong answer on a sentence, find the shortest text that is still wrong. Then trace it by hand, as in lesson 4, and compare each step with what the program does.

The milestones

Everything below is one exercise, with your work in one folder. The folder already holds two files: TextTool.java, which has only the class, an empty main and a comment, and DESIGN.md, which you fill in as you go. There are no method stubs, because writing the headers is part of the work.

work/pa-checkpoint/text-tool/TextTool.java
// Checkpoint project A: TextTool, a command-line text toolkit.
//
// Run as:  java TextTool <command> <text>
//
// Milestones (the full specification is on the checkpoint page):
//   1. Skeleton:  usage message, arrow switch on the command, "Unknown command",
//                 and the text from args[1] onwards joined with single spaces.
//   2. words:     splitWords, then print the words numbered, with a count.
//   3. count:     characters, letters, digits and words, as an aligned summary.
//   4. freq:      letterFrequency, then a bar chart of the letters that occur.
//   5. tally:     distinct words (ignoring case) and how often each occurs.
//   6. stretch:   reverse, longest, and one extension that loops over two lists.
//
// Write the header and a one-line contract for each method in DESIGN.md first.

public class TextTool {

    public static void main(String[] args) {

    }
}
core

Project A · TextTool

Work in work/pa-checkpoint/text-tool/ in your course kit

Build TextTool in the six milestones below, then complete DESIGN.md. A milestone is finished when your program's output matches its sample runs character for character (including spaces) and the edge cases listed for it behave. A test program will call every method whose header is given. It does not call your main and does not care how you wrote the inside of a method. Anything you print goes to System.out, and no line has spaces after its last character.

Milestone 1 · Skeleton

What to build. The main method and one helper.

  • If fewer than two arguments were given, print the usage message below and stop. (A command with no text is too few.)
  • Otherwise args[0] is the command and the text is made from args[1] onwards: args[1], then each later argument with exactly one space before it. Write this as the method below, and have main call it.
  • Choose what to do with an arrow switch on the command (lesson 3). Add a case for each of the seven commands, words, count, freq, tally, reverse, longest and ranked. For now a case may do nothing, or print a placeholder.
  • A command that is not one of the seven prints Unknown command: followed by the command as it was typed. Command names are lower case, so Words is unknown.

Required header. A test program will call it:

static String joinArguments(String[] args, int start) returns args[start] and every later argument, with one space between neighbouring arguments, even when an argument is empty. It returns "" when start is equal to args.length. It may assume start is not negative and not greater than args.length.

Usage message (two lines, printed even though most commands do not exist yet):

Sample run
> javac TextTool.java
> java TextTool
Usage: java TextTool <command> <text>
Commands: words, count, freq, tally, reverse, longest, ranked
> java TextTool words
Usage: java TextTool <command> <text>
Commands: words, count, freq, tally, reverse, longest, ranked
> java TextTool dance
Usage: java TextTool <command> <text>
Commands: words, count, freq, tally, reverse, longest, ranked
> java TextTool dance now
Unknown command: dance
> java TextTool Words hello
Unknown command: Words

Edge cases. No arguments. One argument only. A known command spelt with a capital letter. An unknown command given with several words of text. The argument count is checked before the command is looked at, so java TextTool dance prints the usage message, not Unknown command.

Hint 1

An arrow case needs a statement or a block. If you do not want a case to do anything yet, an empty block, { }, is legal. For joinArguments, the loop starts at start, not at 0. Ask where the space belongs: before each argument, or after each one? Which argument is the one that gets no space?

Hint 2

To see an invisible space, print the result between brackets while you test: System.out.println("[" + joinArguments(args, 1) + "]");. A space at either end shows up inside the brackets. The StringBuilder from lesson 6 is a good tool here.

Milestone 2 · words

What to build. A word is a longest possible run of letters and digits: a stretch of consecutive characters that are all letters or digits, which cannot be made longer in either direction. Every other character, such as a space, a comma, an apostrophe, a hyphen or an underscore, separates words. Words keep their case.

Required header (add import java.util.ArrayList; at the top of the file):

static ArrayList<String> splitWords(String text) returns the words of text, in order, in a new list. It returns an empty list when there are none.

Do not use the split method. Scan the text with charAt in a loop. A character is part of a word when Character.isLetter(c) || Character.isDigit(c) is true. Build each word in a StringBuilder, and add it to the list when it ends.

The words command prints the words numbered from 1, one per line, each as the number, a full stop, a space and the word. The last line is Words: and the count. When there are no words, that last line is the only one. Write a small print... method for the printing, so that splitWords only returns.

Sample run
> javac TextTool.java
> java TextTool words "Hello, world!"
1. Hello
2. world
Words: 2
> java TextTool words "It's 9 o'clock, almost."
1. It
2. s
3. 9
4. o
5. clock
6. almost
Words: 6
> java TextTool words "...!!!"
Words: 0

The apostrophes in It's and o'clock separate words, because an apostrophe is neither a letter nor a digit. That is a consequence of the definition, not a bug, and the milestone checks expect it.

Edge cases. Empty text. Text of spaces only. Punctuation only. Text that starts with a separator. Text that ends with a separator, and text that ends with a word. Two or more separators in a row, which must not produce empty words. Digits inside and next to letters, as in R2-D2. Mixed case.

Hint 1

For each character there are two cases. It belongs to a word, so it goes on the end of the builder. Or it does not, and then a word, if there was one, has just ended. How do you know whether there was one? Once a finished word has gone into the list, the builder must be empty again before the next word starts. Lesson 6 shows no way to empty a builder, so replace it with a new one, new StringBuilder().

Hint 2

Think about the very last character of the text. If it is a letter, nothing after it tells your loop that the word has ended. What is still in the builder when the loop finishes? The hand trace in DESIGN.md makes you work this out on a short text.

Milestone 3 · count

What to build. Three methods, each taking the text:

  • static int countLetters(String text) counts the characters for which Character.isLetter is true.
  • static int countDigits(String text) counts the characters for which Character.isDigit is true.
  • static int countWords(String text) returns the number of words in the text. It must get them by calling splitWords, not by scanning the text a second time. Counting characters needs no method of yours: it is text.length().

The count command prints four lines. Each has a label followed by a colon, and the colon is part of the label: the label with its colon is left-aligned in a column 12 wide, then the number right-aligned in a column 6 wide (use one printf per line, with %-12s and %6d).

Sample run
> javac TextTool.java
> java TextTool count "It's 9 o'clock, almost."
Characters:     23
Letters:        15
Digits:          1
Words:           6
> java TextTool count "   "
Characters:      3
Letters:         0
Digits:          0
Words:           0
> java TextTool count "R2-D2 and C-3PO"
Characters:     15
Letters:         8
Digits:          3
Words:           5

Edge cases. Empty text: all four numbers are 0. Text of spaces: they count as characters and as nothing else. A number made of several digits is several digits but one word. A useful check on any run: letters plus digits cannot be more than the characters.

Hint 1

This is the counting pattern from lesson 4 applied to the characters of a string, twice, with a different question each time. The two methods look almost the same, and that is fine.

Milestone 4 · freq

What to build. static int[] letterFrequency(String text) returns an array of exactly 26 elements. Element 0 holds the number of a and A in the text, element 1 the number of b and B, and so on up to element 25 for z and Z. Only the letters a to z and A to Z are counted. Every other character is ignored, whatever it is: digits, spaces, punctuation, and letters outside the English alphabet such as the é of café.

Use char arithmetic to find the element for a letter (lesson 6). Do not write 26 separate tests, and do not use a switch with 26 cases.

The freq command prints one line for each letter that occurs at least once, in alphabetical order. Each line is the letter in lower case, a space, the count right-aligned in a column 3 wide, a space, and then as many * characters as the count. A count too big for its column is not cut: widths in printf are minimums (lesson 6), so the line is just wider. When no letter occurs, it prints one line, No letters found.. As before, put the printing in a print... method that receives the array.

Sample run
> javac TextTool.java
> java TextTool freq "Mississippi river"
e   1 *
i   5 *****
m   1 *
p   2 **
r   2 **
s   4 ****
v   1 *
> java TextTool freq ZzAa
a   2 **
z   2 **
> java TextTool freq 12345
No letters found.

Edge cases. Text with no letters at all. A mix of capitals and small letters, which must land in the same element. The first and last letters of the alphabet. Characters that sit next to the alphabet in the character table, such as @ (just before A), [ (just after Z), the backtick (just before a; in PowerShell type it inside single quotes, as in 'a`b') and { (just after z): they must be ignored without causing an exception.

Hint 1

What is 'c' - 'a'? What is 'A' - 'a', and so what must you do with a capital letter before using it as an index?

Hint 2

An index that is not between 0 and 25 stops the program with an exception (lesson 7). So a character has to be recognised as a letter before you use it to pick an element. Decide how you will recognise one, then ask what a character like @ would do to your test.

Milestone 5 · tally

What to build. Two methods, both working on a list of words such as the one splitWords returns:

  • static ArrayList<String> distinctWords(ArrayList<String> words) returns a new list with each distinct word once, in lower case, in the order of its first appearance. Words are the same when they are equal without regard to case, so The, THE and the give one entry, the.
  • static int countOf(ArrayList<String> words, String word) returns how many elements of words are equal to word without regard to case.

Neither method may change the list it receives. The test program checks this.

The tally command prints one line for each distinct word: the word left-aligned in a column 10 wide, a space, and the count right-aligned in a column 3 wide. A word longer than 10 characters is not cut, because the width is a minimum: the word is followed by one space and the count, and the counts below it no longer line up. When there are no words it prints No words found.. The printing method calls both of your methods.

Sample run
> javac TextTool.java
> java TextTool tally "the cat and the hat and THE bat"
the          3
cat          1
and          2
hat          1
bat          1
> java TextTool tally "..."
No words found.
> java TextTool tally "extraordinary Extraordinary"
extraordinary   2

This resembles withoutDuplicates from lesson 7's Word tools, and you may adapt your solution to it. The list type is the same. The differences are the case rule and that each word is stored in lower case.

Edge cases. An empty list. A text that is one word repeated in different cases. A word that is a part of another: cat is not the same word as cats. A word that does not occur: countOf returns 0.

Hint 1

To build distinctWords, go through words and, before each add to the new list, ask that list a question. Convert the word to lower case first, so that the question and the stored form agree.

Hint 2

If a test shows that your argument list changed, look for a call that removes or clears. A method should only read the list it is given. The section ArrayList: a list that grows (see Lists are objects too) shows that a method which changes a list it receives changes the caller's list.

Milestone 6 · Stretch

What to build. Three more commands.

reverse. static ArrayList<String> reversedWords(ArrayList<String> words) returns a new list with the same words in the opposite order and does not change its argument. The command prints the reversed words on one line, separated by single spaces, or No words found. when there are none.

longest. static String longestWord(ArrayList<String> words) returns the longest word as it was written, with its original case. When several words share the greatest length, it returns the earliest. It returns "" for an empty list. The command prints Longest word: , the word, , length and the length, or No words found. when there are none. (Both resemble lesson 7 exercises, as listed in The rules, and you may adapt your own solutions.)

ranked. This is the extension, and it needs a hand-written loop over two lists that must stay in step. The command prints the tally of milestone 5, in the same format, but with the most frequent word first. Words with equal counts stay in the order of their first appearance. With no words it prints No words found., like the other two. Two methods are required:

  • static ArrayList<Integer> countsFor(ArrayList<String> distinct, ArrayList<String> words) returns a new list in which element i is the number of times distinct.get(i) occurs in words, ignoring case. The two lists, distinct and the result, are parallel lists: position i in each describes the same word.
  • static void sortByCount(ArrayList<String> words, ArrayList<Integer> counts) reorders both lists, in place, so that the counts descend and every word is still next to its own count. Elements with equal counts keep their relative order; a sort with that property is called stable. It returns nothing.

No library sorting is allowed, in any form. You write the loops. Beware of comparing two Integer values with ==: lesson 7's section Lists of numbers: wrapper types shows what goes wrong. Compare them as ints, or with equals.

Sample run
> javac TextTool.java
> java TextTool reverse "one two three four"
four three two one
> java TextTool reverse "!!!"
No words found.
> java TextTool longest "a bb cc ddd eee"
Longest word: ddd, length 3
> java TextTool ranked "a b b c c c"
c            3
b            2
a            1
> java TextTool ranked "x y z"
x            1
y            1
z            1
> java TextTool ranked "to be or not to be"
to           2
be           2
or           1
not          1
> java TextTool ranked "!!!"
No words found.

Edge cases. No words, for all three commands. One word. A tie for longest between two words, and a tie between a word made of letters and one made of digits. All counts equal, so that the order must not change at all. Large counts, above 127, where the Integer trap of lesson 7 can show itself: your sorting method must work when two equal counts are large.

Hint 1

Whatever you do to position i of one list, you must also do to position i of the other, or the words and counts drift apart. Work out on paper how you would move one entry earlier in both lists while keeping the others in order.

Hint 2

Take the entries from the second position onwards, one at a time. Hold the current word and count in two variables, slide earlier entries one place along while their count is smaller than the one you hold, and then put the held pair down in the gap. Think about why this keeps equal counts in their original order, and what would happen if you slid past entries whose counts were equal.

The written part · DESIGN.md

Fill in the four parts of DESIGN.md, in your own words. Write part 1 before the code of each milestone, parts 2 and 3 as you go, and part 4 at the end.

  1. Methods. For every method you wrote: its header exactly as in your code, and a one-sentence contract. Note any entry whose header or contract you changed later, and why.
  2. Hand trace. A table to complete: trace your splitWords by hand on the text ..up-to 9 (nine characters), one row per character, showing what the builder and the list hold afterwards. A last row is for the state after the loop. Then say which word would be missing from the final list if the step after the loop were left out, and why. Do this before you run your method on that text.
  3. Test log. At least eight rows from your own testing, across at least four milestones, including at least one test that failed and what you changed.
  4. Reflection. Four questions are in the file. They ask why splitWords returns a list and not an array, what would change if the definition of a word changed, what you would have to touch to add a new command, and what returning a result instead of printing it gave you in this project.

To check it, run python check.py pa in your course kit folder, or for one milestone, python check.py pa m3.

How it will be reviewed

In your course kit folder, run python check.py pa to check every milestone, or python check.py pa m3 for one of them. The checker reports facts only: whether each milestone compiles, whether its sample runs produce the expected output, whether its hidden method tests pass, and whether DESIGN.md exists and is not empty. Nobody reads your code or your design notes, so judging them is your job. Before you call a milestone finished, go through these points yourself, in this order:

If your code passes the checker and meets these points, it is correct, even if another solution looks different. If a point fails, find the line it concerns, work out which idea from the lessons applies, and change it yourself.

Summary

Words introduced in this project

TermMeaning
MilestoneA stage of a project that adds one working piece and can be checked on its own.
ContractA sentence saying what a method returns and what it assumes about its arguments.
Word (in this project)A longest possible run of letters and digits.
Parallel listsTwo lists in which position i of each describes the same item.
Stable sortA sort that keeps items with equal keys in their original order.
Hand traceWorking through a method on paper, one step at a time, recording what each variable holds.