我写了一个二叉树程序,询问用户有关某些动物的问题。
我的问题是当我的程序询问用户“继续?”我希望循环再次开始,但我不知道如何实现这一点。它在我的while循环中出现两次,在底部出现在我的learn方法中。有没有人对我如何做到这一点有任何想法?
import java.util.*;
public class AnimalGuessing {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
TreeNode<String> leftTree = new TreeNode<String> ("cat");
TreeNode<String> rightTree = new TreeNode<String> ("snake");
TreeNode<String> gameTree = new TreeNode<String>( "Does it have legs?",leftTree,rightTree);
TreeNode<String>curr = gameTree;
String response;
System.out.println("");
System.out.println("");
System.out.println("Think of an animal and I will guess it.");
while(!(curr.getLeft() == null && curr.getRight()==null)){
System.out.print(curr.getItem());
response = scan.nextLine();
if (response.equals("YES")){
curr = curr.getLeft();
System.out.print("Is it a " + curr.getItem() + "?");
response = scan.nextLine();
if (response.equals("YES")){
System.out.println("I win! Continue?");
response = scan.nextLine();
if (response.equals("YES")){
//-----------------------
// I want it to restart
// the while loop here!
//-----------------------
}
else{
System.out.println("Good-bye.");
}
}
else{
learn(curr);
}
}//end if
if (response.equals("NO")){
curr = curr.getRight();
System.out.println("is it a " + curr.getItem() + "?");
response = scan.nextLine();
if (response.equals("YES")){
System.out.println("I win! Continue?");
response = scan.nextLine();
if (response.equals("YES")){
//-----------------------
// I want it to restart
// the while loop here!
//-----------------------
}
else{
System.out.println("Good-bye.");
}
}
else{
learn(curr);
}
}
}//end while
}//end main
//----------------------------------
//
// Use to add new animals/questions
// to the tree.
//
//----------------------------------
public static void learn(TreeNode<String> current){
Scanner scan = new Scanner(System.in);
String guessAnimal; // animal just guessed guessed
String correctAnimal; // animal user was thinking of
String newQuestion; // A question to distinguish the two
String response;
// Set Strings for the guessed animal and correct animal and a new question.
guessAnimal = current.getItem();
System.out.print("I give up. What is it? ");
correctAnimal = scan.nextLine( );
System.out.println("Please type a question whose answer is yes for a " +correctAnimal);
System.out.print("and no for a " + guessAnimal + ".");
newQuestion = scan.nextLine( );
// Put the new question in the current node, and add two new children.
current.setItem(newQuestion);
current.setLeft(new TreeNode<String>(correctAnimal, null, null));
current.setRight(new TreeNode<String>(guessAnimal, null, null));
System.out.println("Continue?");
response = scan.nextLine();
if (response.equals("YES")){
//--------------
//I want it to
//restart here!
//--------------
}
else{
System.out.println("Good-bye.");
}
}//end learn
}//end AnimalGuessing
答案 0 :(得分:4)
如果它的作业我不会写答案但是解释
你想做什么来围绕该代码添加一个循环
然后你需要添加一个条件来退出循环(比如boolean loopAgain)
这样当你想重新开始冒险时,你将布尔值设置为true
如果用户已完成,则将布尔值设置为false。