import java.util.Scanner; public class TwentyQuestions { public static void main(String[] args) { new TwentyQuestions().run(); } public void run() { saveTree(startGame(preloadTree())); } private QuestionNode startGame(QuestionNode root) { System.out.println("Let me guess the object in your mind."); Scanner userInput = new Scanner(System.in); do { root = playingGame(root, userInput); } while (isPlayGameAgain(userInput)); System.out.println("Goodbye~"); return root; } private boolean isPlayGameAgain(Scanner userInput) { System.out.println("Do you want to play the game again?"); String isPlay = userInput.nextLine(); return isPlay.toLowerCase().equals("yes"); } private QuestionNode playingGame(QuestionNode root, Scanner userInput) { if (root.isQuestion()) { System.out.println(root.getContent()); String answer = userInput.nextLine(); if (answer.toLowerCase().equals("yes")) { root.left = playingGame(root.left, userInput); } else { root.right = playingGame(root.right, userInput); } } else { System.out.println("Is it a(n) " + root.getContent() + "?"); String answer = userInput.nextLine(); if (answer.toLowerCase().equals("yes")) { System.out.println("I won!"); } else { System.out.println("I lose. What's your object?"); QuestionNode computerGuess = root; QuestionNode objectInMind = new QuestionNode(userInput.nextLine(), false); System.out.println( "Type a yes/no question to distinguish your item from " + computerGuess.getContent() + ":"); root = new QuestionNode(userInput.nextLine(), true); System.out.println("And what is the answer for your object?"); answer = userInput.nextLine(); if (answer.toLowerCase().equals("yes")) { root.left = objectInMind; root.right = computerGuess; } else { root.left = computerGuess; root.right = objectInMind; } } } return root; } private QuestionNode preloadTree() { // Change code below to load tree from a file by using pre-order QuestionNode root = new QuestionNode("apple", false); return root; } private void saveTree(QuestionNode root) { // save tree by using pre-order to a file } }