import java.util.Scanner; /****************************************************** * Created by Chad Milburn, November 2007. * * Class created for a CS lab, designed to be a * * learning method similar to the game 20 questions. * * Uses recursion and tree to accomplish this. * ******************************************************/ public class QNode { private String value; // Contains question. private String name; // Contains guess (animal). private QNode y; // Yes branch. private QNode n; // No branch. public static void main(String[] args) { Scanner in; boolean has; QNode first = new QNode(); // Create first QNode. first.value = "Does it have legs?"; // Add first question. first.y = new QNode(); // Create first Y branch. first.y.name = "cat"; // Add 'cat'. first.n = new QNode(); // Create first N branch. first.n.name = "snake"; // Add 'snake'. do // Loop until 'quit' is entered. { first.branch(); System.out.println("Play again or quit?"); in = new Scanner(System.in); has = in.nextLine().trim().toLowerCase().contains("quit"); } while(!(has)); System.out.println("Thanks for playing, have a nice day."); } /***************************************************************** * Recursive method contains a question (value), animal (name), * * and 2 nodes for answers to the question. If the question * * is empty, it asks if the animal is (name). Yes returns to * * base case and starts again. No adds a new animal and * * question, and 2 new nodes for answers. * *****************************************************************/ public void branch() { Scanner in = new Scanner(System.in); String input; if(value != null) // Keep traversing branches. { System.out.println(value); // Ask question. input = in.nextLine().trim().toLowerCase(); if (input.contains("yes")) y.branch(); // Yes branch. else n.branch(); // No branch. } else if(value == null) // Reached end of branch. { System.out.println("Is it a/an " + name + "?"); //Guess animal. input = in.nextLine().trim().toLowerCase(); if(input.contains("yes")) // Animal found. Return to base. { System.out.println("All your base are belong to us."); } else // Guess is incorrect, add new animal. { System.out.println("I give up."); System.out.println("What is your animal?"); String newName = in.nextLine().trim().toLowerCase(); System.out.println("What is a question that you " + "would answer no to " + newName + ", but " + "yes to " + name + "?"); String newQuestion = in.nextLine().trim(); y = new QNode(); y.name = name; n = new QNode(); n.name = newName; name = null; value = newQuestion; System.out.println("Your animal, " + newName + ", has been added to my databanks."); } } } }