If you enter the text of Hamlet into a Map structure, you might like to use that structure to produce a Concordance, that, traditionally, would begin something like this:
a occurs 571 times abate occurs 1 times abatements occurs 1 times abhorred occurs 1 times ability occurs 1 times able occurs 1 times aboard occurs 3 times abominably occurs 1 times about occurs 18 times above occurs 4 times abridgment occurs 1 times abroad occurs 1 times absent occurs 1 times absolute occurs 2 times abstinence occurs 1 times abstract occurs 1 times absurd occurs 2 times abus occurs 1 times abuse occurs 1 times abuses occurs 1 times accent occurs 2 times accepts occurs 1 times access occurs 1 times
I will use the word "concordance" to describe a file that lists all the words in alphabetic order together with a count of how often they occurred. Above you see an early part of the concordance I want you to produce for Hamlet.
I want you to add a new button so you can produce a concordance in the Console.
Then let's modify it so you print the concordance to a file. It's not hard to do. The code you need is here (but you'll need to put it in the right place!)
traverse will be just like inOrder but you'll add a parameter for a PrintStream.
private concordance;
concordance = new JButton("Make a concordance");
buttonPanel.add(concordance);
And, of course, you'll need a listener so the button works. Here's that code:
concordance.addActionListener(new ActionListener() {
public void actionPerformed (ActionEvent e) {
PrintStream ps = null;
try {
ps = new PrintStream(new File(data.getText()));
}
catch (Exception e2) {}
myTree.traverse(ps);
ps.close();
}
});
You may want to be a little more polite than I am about catching the exception. Notice what this action is: When the button is clicked:
Observe that in order for this class to compile now you will need to add the traverse method to the ATree interface. That's easy: Add this line to the file.
public void traverse(java.io.PrintStream ps);
Now, of course, ETree and Tree must implement the traverse method. Here's my code for Tree:
/**
* traverse -- inorder traversal, printing my data
*/
public void traverse(java.io.PrintStream ps) {
ps.println(myData.toString() + " occurs "+count+" times");
left.traverse(ps);
right.traverse(ps);
}
The only problem is that I've given you code for a preorder traversal. That's not what you need if you want your concordance to be printed in
alphabetic order. (Hint: you need to reorder the lines of code to get the
traversal you want.)I'm going to let you write your own code for the traverse method in the ETree class. (Hint: That's not asking very much at all, is it?)