Question

In: Computer Science

In java, implement an animal guessing game. Start with a "Decision Tree", but present the leaves...

In java, implement an animal guessing game. Start with a "Decision Tree", but present the leaves as “Is it a X?” If it wasn't, ask the user what the animal was, and ask for a question that is true for that animal but false for X. For example,
Is it a mammal? Y
Does it have stripes? N
Is it a pig? N
I give up. What is it? A hamster
Please give me a question that is true for a hamster and false for a pig.
Is it small and cuddly?

In this way, the program learns additional facts.

Once complete, add to the program by writing the tree to a file when the program exits. Load the file when the program starts again.

Solutions

Expert Solution

BinaryTree.java

/**
* This class creates a Binary Tree that hold Nodes filled with a String.
*  *
*/
public class BinaryTree {
   /**
   * Default Constructor, sets root and current to null.
   */
   BinaryTree(){
       root = null;
       current = null;
      
   }
  
   /**
   * Inserts String info into Binary Tree based on String Move using a private
   * recursive function.
   * @param info Value to be inserted into Binary Tree
   * @param move Value that is considered in order to properly place info
   */
   void Insert(String info, String move){
       root = InsertItem(root, info, move);
   }
  
   /**
   * Prints out the Binary Tree using private recursive function
   */
   void Print(){
       PrintTree(root);
   }
  
   /**
   * Evaluates whether or not Binary Tree is empty or not
   * @return trueOrfalse True if root equals null
   */
   boolean isEmpty(){
       if (root == null){
           return true;
       }
       else{
       return false;
       }
      
   }
  
   /**
   * Evaluates whether or not current is located at a ending leaf/child node
   * @return trueOrfalse True if current has to nodes to travel to
   */
   boolean isAtEnd(){
       if ((current!= null) && (current.left == null && current.right == null)){
           return true;
       }
       else{
           return false;
       }
   }
   /**
   * Returns the value of the current node
   * @return current.data The string located in the current node.
   */
   String getCurrentData(){
       return current.data;
      
   }
  
   /**
   * Moves current pointer to the following right node, signaling a YES
   */
   void moveCurrentYes(){
       current = current.right;
   }
  
   /**
   * Moves current pointer to the following left node, signaling a NO
   */
   void moveCurrentNo(){
       current = current.left;
   }
   /**
   * Moves current to root, the starting point.
   */
   void setCurrentToStart(){
       current = root;
      
   }
  
   //Recursive Functions
   /**
   * Inserts String value into the appropriate node.
   * If newRoot is not fill then this method will fill it recursively
   * @param newRoot node that is considered for insertion
   * @param value String to be inserted into new Node
   * @param move String that determines where to place other String values
   * @return newRoot The node that was inserted into the Binary Tree
   */
   private Node InsertItem(Node newRoot, String value, String move){
       if (newRoot == null)
{
           newRoot = new Node(value);
//           System.out.println("ROOT INSERTED");
           return newRoot;
       }
else if (move == "Y"){
//    System.out.println("YES INSERTED");
           newRoot.right = InsertItem(newRoot.right, value, move);
       }
       else{
       //   System.out.println("NO INSERTED");
           newRoot.left = InsertItem(newRoot.left, value, move);
       }
       return newRoot;
   }
     
   /**
   * Prints the Binary Trees values in a preorder traversal
   * @param root Starting node of the tree
   */
   private void PrintTree(Node root){
       if (root != null){
           System.out.println(root.data);
           PrintTree(root.left);
           PrintTree(root.right);
       }
   }
  
   //Data Members
   protected Node root; //Starting Point of Binary Tree
   protected Node current; //Current position

}

BinaryTree.java

import java.util.*;
/**
* This class creates a "Bot" that operates as the programs voice and prompter.
* It creates a new Binary Tree and manipulates it using methods belonging to the BinaryTree class.
* This "Bot" will ask the questions and insert answers into a Binary Tree.
* It will keep guessing until it gives up or reaches a correct answer.
* @
*
*/
public class Bot{
   Scanner in = new Scanner(System.in); //Open input stream
   /**
   * Default Constructor, creates a new Binary Tree
   */
   Bot(){
       GuessTree = new BinaryTree();
   }
   /**
   * This method asks the user questions and will try to guess what the animal is.
   */
   void askQuestion(){
       String animal;
       String question;
       char YorN;
       if (GuessTree.isEmpty()){
           /*TREE IS EMPTY*/
           giveUp();
           //System.out.println(root.data);
       }
       else if (GuessTree.isAtEnd()){
           /*AT END NODE*/
           //System.out.println("END");
           animal = GuessTree.current.data;
           question = "Is it " + AorAn(animal) + " " + animal + "?";
           //DoWhile loop to check character entered and allow user to re-enter valid arguments
           do{
           System.out.println(question);
           YorN = in.nextLine().toUpperCase().charAt(0);
           if (YorN == 'Y'){
               System.out.println("I win!");
               GuessTree.setCurrentToStart();
           }
           else if (YorN == 'N'){
               giveUp();
           }
           else{
               System.out.println("Invalid Character. Try Again.");
           }}while(YorN != 'Y' && YorN != 'N');
       }
       else{
           /*ASKING QUESTION*/
           //System.out.println("ASKING");
           question = GuessTree.current.data;//Question Node
           //DoWhile loop to check character entered and allow user to re-enter valid arguments
           do{
           System.out.println(question);
           YorN = in.nextLine().toUpperCase().charAt(0);
           if (YorN == 'Y'){
               GuessTree.moveCurrentYes();
               askQuestion();
           }
           else if (YorN == 'N'){
               if(GuessTree.current.left == null){
                   giveUp();
                  
                  
               }
               else{
                   GuessTree.moveCurrentNo();
                   askQuestion();
               }
           }
           else{
               System.out.println("Invalid Character. Try Again.");
           }
       }while(YorN != 'Y' && YorN != 'N');
       }
   }
   /**
   * If the Bot cannot guess the correct animal, it will give up and ask
   * the user to input the animal and a question that describes it.
   */
   void giveUp(){
       String oldAnimal; //guessed Animal
       String animal; //new Animal
       String question; //Concatenated String
       String newQuestion; //new Question
       System.out.println("I give up. What is it? ");
       animal = in.nextLine();
       question = "What question would tell me it is "
                   + AorAn(animal) + " " + animal + "?";
       System.out.println(question);
       newQuestion = in.nextLine();
       /*IF BINARY TREE IS EMPTY*/
       if (GuessTree.isEmpty()){
           //moves new question to the right
           GuessTree.Insert(newQuestion, "Y");
           //moves new animal to the right
           GuessTree.Insert(animal, "Y");
           GuessTree.setCurrentToStart();
       }
       /*IF CURRENT POINTER IS AT STARTING NODE
       *AND USER ENTERS NO FOR FIRST QUESTION*/
       else if( GuessTree.current.data == GuessTree.root.data){
           //moves new question to the left
           GuessTree.Insert(newQuestion, "N");
           //set current pointer to the new question node
           GuessTree.moveCurrentNo();
           //moves new animal to the right of new question
           GuessTree.current.right = new Node(animal);
           GuessTree.setCurrentToStart();
          
       }
       else{
           /*IF NODE IS A QUESTION*/
           if(GuessTree.current.data.contains("?")){
               //Create new left node
               GuessTree.current.left = new Node(newQuestion);
               //Create new left.right node
               GuessTree.current.left.right = new Node(animal);
               GuessTree.setCurrentToStart();
           }
           /*IF GUESSED ANIMAL IS WRONG*/
           else{
               //oldAnimal is the animal guess by the Bot
               oldAnimal = GuessTree.current.data;
               //the new question replaces the oldAnimal node
               GuessTree.current.data = newQuestion;
               //the oldAnimal is pushed to the left
               GuessTree.current.left = new Node(oldAnimal);
               //the new correct animal placed to the right
               GuessTree.current.right = new Node(animal);
               GuessTree.setCurrentToStart();
           }
       }
      
   //   GuessTree.Print();

   }
   /**
   * This method places correct grammatical structure, a or an, in front of an animal string.  
   * @param animal The animal that needs to be analyzed
   * @return aOran an if the animal's first letter begins with a vowel, a for anything else
   */
   String AorAn(String animal){
       Character firstLetter;
       //Array of Vowels
       ArrayList<Character> vowels = new ArrayList<Character>();
       vowels.add('A');
       vowels.add('E');
       vowels.add('I');
       vowels.add('O');
       vowels.add('U');
      
       firstLetter = animal.toUpperCase().charAt(0);
      
       if (vowels.contains(firstLetter)){
           return "an";
       }
       else{
           return "a";
       }
      
   }
   BinaryTree GuessTree; //Binary Tree for storing questions and answers
}

GameMain.java

import java.util.*;

/**
* This is the main class that instantiates the Bot class and begins the guessing game.
* It will ask the user if he or she has thought of an animal.
* Also it will ask the user to play again after he or she finishes a game.
* @
*
*/
public class GameMain {

   /**
   * Main that begins the guessing game
   * @param args
   */
   public static void main(String[] args) {
       // TODO Auto-generated method stub
       Bot GuessBot = new Bot();
       char charChoice;//Y or N to start game
       char charEnd;//Y or N to play again

       Scanner in = new Scanner(System.in);
      
       System.out.println("Hello! I will do my best to guess your animal!");
      
       do{//DoWhile loop to check character entered and allow user to re-enter valid arguments
       System.out.println("Ok. Think of an animal. Ready? ('y' to continue)");
       charChoice = in.nextLine().toUpperCase().charAt(0);
       if (charChoice == 'Y'){
           do{//Ask questions
           GuessBot.askQuestion();
          
           do{//DoWhile loop to check character entered and allow user to re-enter valid arguments
           System.out.println("Would you like to play again? (y/n)");
           charEnd = in.nextLine().toUpperCase().charAt(0);
           if (charEnd != 'Y' && charEnd != 'N'){
               System.out.println("Invalid Character.");
           }}while(charEnd != 'Y' && charEnd != 'N');
           }while(charEnd != 'N');
       }
       else if(charChoice == 'N'){
           System.out.println("I'll wait.");
       }
       else{
           System.out.println("Invalid Character. Try Again.");
       }
       }while(charChoice != 'Y');
      
       in.close(); //Closes input stream
   }

}

Node.java

/**
*
*/

/**
* This class creates a Node that holds a String and left,right nodes.
* @author
*/
public class Node {

   /**
   * Default Constructor, sets left and right nodes to null
   */
   Node(){
       left = null;
       right = null;
   }
   /**
   * Non-default Constuctor, sets left and right nodes to null and sets String data to info
   * @param info String value
   */
   Node(String info){
       left = null;
       right = null;
       data = info;
      
   }
  
   protected Node left;
   protected Node right;
   protected String data;
  
  
}


Related Solutions

guessing game in Java. It will have a guess input used for guessing the random number...
guessing game in Java. It will have a guess input used for guessing the random number that is generated from 1 - 100. When the user makes a guess it will tell them if the number is lower or higher than the guess. There is also a choice to give up which then reveals the correct number. The last choice will be new game which resets the random number. Last, the program should keep counts of tries. When the user...
Java program that uses binary tree and recursions to implement Tower of Hanoi game where there...
Java program that uses binary tree and recursions to implement Tower of Hanoi game where there can be any amount of disks and there are either 3,4, or 5 pegs to store the disks(# of pegs and disks is manually inputted by user), in Tower of Hanoi game, the object of the game is move all the pieces from the 1st peg to the right most peg or the opposite side. You can place disks on top of each other...
This is for java For my assignment, I was supposed to make a number guessing game....
This is for java For my assignment, I was supposed to make a number guessing game. The class, HiLo, should pick a random number between 1 and 100 (inclusive). Then, prompt the user to guess the number. On each guess, print if the user is correct or if the guess is too high or too low. Allow only 5 guesses. In the end, print out the correct answer and how many attempts were made. Then give the user the option...
Java guessing game: For this program you will use Linear Search. - Ask the user to...
Java guessing game: For this program you will use Linear Search. - Ask the user to choose between a number from 0 to 2000. - The user will guess how long the linear search will take in nanoseconds, - After the user puts in their answer, show the user the difference between the actual answer and their answer. (Example: The user puts in 5 nanoseconds. The actual time is 11 nanoseconds. The program will show 6 nanoseconds.) There should be...
JAVA Write a number guessing game that will generate a random number between 1and 20 and...
JAVA Write a number guessing game that will generate a random number between 1and 20 and ask the user to guess that number. The application should start by telling the user what the app does. You should then create the random number and prompt the user to guess it. You need to limit the number of times that the user can guess to 10 times. If the user guesses the number, display some message that tell them that they did...
In JAVA Create a simple guessing game, similar to Hangman, in which the user guesses letters...
In JAVA Create a simple guessing game, similar to Hangman, in which the user guesses letters and then attempts to guess a partially hidden phrase. Display a phrase in which some of the letters are replaced by asterisks: for example, G* T*** (for Go Team). Each time the user guesses a letter, either place the letter in the correct spot (or spots) in the phrase and display it again or tell the user the guessed letter is not in the...
In JAVA, write a number guessing game that randomly assigns a integer between one and twenty...
In JAVA, write a number guessing game that randomly assigns a integer between one and twenty for the user to guess. Write three methods to make this particular program work. 1. Have a method which generates a random number and returns the value to the main (stored as a variable) 2. Have a method which prompts the user for a guess. Return the guess to the main. 3. Evaluate the guess and the random "secret" number by parameters, and then...
in java Create simple number guessing game as follows. First, prompt the user to enter a...
in java Create simple number guessing game as follows. First, prompt the user to enter a min and max value. In your code, declare and assign a variable with a random integer in this range (inclusive). Then, ask the user to guess the number. Input the user's guess. And at the end output "Correct!" if the user's guess was right on spot, or "Sorry, the answer is not corrcet.” The number I was looking for was xxx. Replace xxx with...
I am wanting to know how to write guessing game program in java that prompts the...
I am wanting to know how to write guessing game program in java that prompts the use to enter a capital for a each of 50 states, one state at a time. Upon receiving the user input, the program reports whether the answer is correct or incorrect. Assume 50 states and their capitals are stored in a two-dimensional array. Attached is a copy of the two-dimensional array that can be copied into your program. The user's answer is not case...
How do you implement an AVL tree for strings in Java?
How do you implement an AVL tree for strings in Java?
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT