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
chararithmetic into anint[], 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.
> 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:
> 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:
> 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.
> 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:
> 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.
> 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.
- One file. Everything goes in
TextTool.java, in one class calledTextTool. You may add as many methods as you like. - Only static methods. You have not met anything else for methods yet (that is lesson 8). No classes of your own.
- All input comes from the command line, through
args, as in the section String[] args at last. NoScanner. - Calculating methods return their result. Only
mainand small methods whose names start withprintmay print, as the section Printing versus returning advised. A method such assplitWordsorcountOfthat printed would be useless to the next milestone. - Left out on purpose: the
splitmethod ofString, regular expressions,tryandcatch, streams and lambdas. You have not met them, and milestone 2 is an exercise in doing by hand whatsplitwould do for you. No library sorting either (noArrays.sortor anything like it): milestone 6 asks you to write the loops yourself. Use only what lessons 1 to 7 taught. (Character.isLetterOrDigitis one method you have not seen. It is in the same family asCharacter.isLetterandCharacter.isDigitfrom lesson 6, asks the combined question, and you may use it.) - A comment above every method saying what it does, what it needs and what it returns, as lesson 5 advised. It is part of the review.
- Exact headers. Where this page gives a method header, use it as written. A test program that you cannot see calls those methods, as in lessons 5 to 7, so a different method name, parameter type or return type will not compile against it. (A different parameter name would compile, but keep the names on this page so that your
DESIGN.mdand the page agree.) - Plain English text. The checks use letters from
atoz, digits, spaces and ordinary punctuation. The one exception is stated in milestone 4.
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.
| Milestone | Builds on |
|---|---|
| 1 · Skeleton | Lesson 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 · words | Lesson 6: looping over a string and the Character methods, and StringBuilder. Lesson 7: ArrayList. Lesson 4: building up a result across passes. |
3 · count | Lesson 4: the counting pattern. Lesson 6: printf. Lesson 5: methods that do one job, here by calling the method from milestone 2. |
4 · freq | Lesson 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 · tally | Lesson 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 · stretch | Lesson 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.
countLettersandcountDigits(milestone 3) resemble lesson 6'sPassword rules
in testing each character of a string with theCharactermethods. The counting pattern itself is lesson 4's.distinctWords(milestone 5) resembleswithoutDuplicatesin lesson 7'sWord tools
, with the same list type. It differs in that words are compared without regard to case, and each is stored in lower case.reversedWordsandlongestWord(milestone 6) resemblereversedCopyin lesson 7'sReverse in two ways
andlongestinWord tools
. They differ in the parameter:reversedCopytakes anint[], andlongesttakes varargs, where these take anArrayList<String>.reversedWordsalso returns anArrayList<String>, wherereversedCopyreturns anint[].
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.
- 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.
- 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
. A contract, in this sense, is that sentence: what the caller may rely on. ThetextDESIGN.mdfile has a table for them. If you cannot write the sentence, you are not ready to write the method. - 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.
- Test each method alone before you build on it. Put a temporary line at the top of
mainthat 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
}- 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.
- When something is wrong, make the input smaller. If
wordsgives 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.
// 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) {
}
}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 fromargs[1]onwards:args[1], then each later argument with exactly one space before it. Write this as the method below, and havemaincall it. - Choose what to do with an arrow
switchon the command (lesson 3). Add acasefor each of the seven commands,words,count,freq,tally,reverse,longestandranked. 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, soWordsis 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):
> 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.
> 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 whichCharacter.isLetteris true.static int countDigits(String text)counts the characters for whichCharacter.isDigitis true.static int countWords(String text)returns the number of words in the text. It must get them by callingsplitWords, not by scanning the text a second time. Counting characters needs no method of yours: it istext.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).
> 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.
> 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, soThe,THEandthegive one entry,the.static int countOf(ArrayList<String> words, String word)returns how many elements ofwordsare equal towordwithout 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.
> 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 timesdistinct.get(i)occurs inwords, ignoring case. The two lists,distinctand 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.
> 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.
- 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.
- Hand trace. A table to complete: trace your
splitWordsby 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. - 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.
- Reflection. Four questions are in the file. They ask why
splitWordsreturns 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:
- Correctness. Does each milestone do what the page says, including the edge cases? The tests cover many of them, but not all.
- Methods and reuse. Does each method do one job? Does
countWordsusesplitWords? Do the later commands start from the methods of earlier milestones, or has the same loop been written again? - The rules. One file, static methods only, nothing left out of the language that the rules forbid, and no printing inside a method that should return.
- Clarity. Names that say what things are, short methods, a comment above each method saying what it does, and a layout someone else can read.
- The written design. Do the headers and contracts in
DESIGN.mdagree with the code? Is the trace right? Does the log show what you really tested? Are the reflection answers specific to your program?
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
- A program of this size is a set of small methods that each do one job and return their result. Because they return instead of printing, the later milestones could reuse them:
splitWordsserves six of the seven commands (all butfreq), andcountOfis used by bothtallyandranked. - Splitting text into words is a loop with a state: a builder holding the word so far. The step after the loop, which finishes the last word, is the classic place to go wrong.
chararithmetic turns a letter into an array index, but only after you have made sure it is a letter.- A method that receives a list can change it for its caller. Methods that only read a list must be written so that they do not.
- Two lists that describe the same things need to be changed together. That is the hardest idea in the stretch milestone, and the reason a sort of one list alone is not enough.
- Writing a header and a contract before the code, testing each method on its own, and keeping a log are habits that matter more as programs grow.
Words introduced in this project
| Term | Meaning |
|---|---|
| Milestone | A stage of a project that adds one working piece and can be checked on its own. |
| Contract | A 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 lists | Two lists in which position i of each describes the same item. |
| Stable sort | A sort that keeps items with equal keys in their original order. |
| Hand trace | Working through a method on paper, one step at a time, recording what each variable holds. |