After you know how to write to a file and read from a file, the I/O aspects of the assignment will be straightforward. This will be the subject of the final lab.
Using a preorder printing algorithm, writing the tree to a file will be easy. Reading the data from a file to reconstruct the tree is not as easy to figure out, but can be done with hardly any more code than writing. Hints to follow.
For now, I suggest a convenient format for printing the tree that will help in reading it in. The idea will be to simply print the contents of each node, in preorder, on a separate line. If the node is a leaf, in addition to the contents of the node (which will be a String giving the name of an animal, such as "Cat" or "Mouse" or "Humpback whale"), tack on a semicolon at the end of the line. (We'll make the reasonable assumption that animal names do not end with semicolons.) For example, a printout of the initial tree in the existing program would look like this:
Are you a mammal? Are you bigger than a cat? Kangaroo; Mouse; Do you live underwater? Trout; Robin;or, to reveal the structure of the tree, in indented form:
Are you a mammal?
Are you bigger than a cat?
Kangaroo;
Mouse;
Do you live underwater?
Trout;
Robin;
This simple convention makes it fairly easy to read the tree in -- honest! Why? Because it's easy to determine if a line represents a leaf of the tree. The rest is recursion. How would you construct the tree manually from the above lines? Think about it...
One way to begin work immediately (without worrying about file input or output) would be be add a method to AnimalGuess.java that prints the tree out to the screen, with the semicolons as above. (Make it in indented form for now. This is convenient for debugging, although ultimately when you write to a file you will not want the indented form.)
After "teaching" my decision tree some new questions for a while, the tree file looked like this. The program itself becomes a way of building up an initial tree of significant size. But it'll take a lot of (tedious) work to really make it a game of twenty questions!
Submit: A BlueJ project.