// C Sc 127B. Spring 2007 Project due 10-April-2007 @ 10:00pm // // Complete this game tree class according to the specification // found as Project9: Game of 20 Questions // import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class GameTree { public static void main(String[] args) { String fileWithQandA = "animals.txt"; System.out.println("You are to answer questions until you find an answer"); System.out.println("that you seek. If you don't find it, enter a new"); System.out.println("question and the answer. Current file with"); System.out.println("game questions and answers: " + fileWithQandA); // Create the game tree using the input files GameTree aGame = new GameTree(fileWithQandA); // And show the new tree sideways aGame.printSideways(); } private class BinaryTreeNode { // instance variables private String data; private BinaryTreeNode left; private BinaryTreeNode right; BinaryTreeNode() { data = null; left = null; right = null; } BinaryTreeNode(String theData) { data = theData; left = null; right = null; } BinaryTreeNode(String theData, BinaryTreeNode leftLink, BinaryTreeNode rightLink) { data = theData; left = leftLink; right = rightLink; } } // end class BinaryTreeNode private BinaryTreeNode root; private Scanner my_inputFile; public GameTree(String fileName) { try { my_inputFile = new Scanner(new File(fileName)); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } root = build(); } private BinaryTreeNode build() { // pre: input readable (Based on the C++ // version by Owen Astrachan) // post: returns tree constructed from reading file String s = null; BinaryTreeNode tree = null; BinaryTreeNode left = null; BinaryTreeNode right = null; if (my_inputFile.hasNextLine()) { s = my_inputFile.nextLine().trim(); if (s.indexOf("?") > 0) { // add a question left = build(); // process yes branch right = build(); // process no branch tree = new BinaryTreeNode(s, left, right); } else { // Call one argument constructor tree = new BinaryTreeNode(s); // add an answer } } return tree; } public void printSideways() { int depth = 0; System.out.println(); printSideways(root, depth); } private void printSideways(BinaryTreeNode t, int depth) { if (t != null) { printSideways(t.right, depth + 1); for (int j = 1; j <= depth; j++) System.out.print(" "); System.out.println(t.data.toString()); printSideways(t.left, depth + 1); } } }