2010-12-17 4 views
1

Я написал программу двоичного дерева, которая задает вопросы пользователю, чтобы узнать о некоторых животных.Перезапуск цикла while/программы

Моя проблема заключается в том, что когда моя программа запрашивает пользователя «Продолжить?» Я хочу, чтобы цикл начинался снова, но я не уверен, как это сделать. Это происходит дважды в моем цикле while и один раз в моем методе обучения внизу. Есть ли у кого-нибудь идеи о том, как я могу это сделать?

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 

ответ

4

, если его домашнее задание, я не буду писать ответ, но объяснить

Что вы хотите сделать это, чтобы добавить петлю вокруг этого кода

, то вам нужно добавить условие, чтобы выйти из цикл (как логическое loopAgain)

таким образом, если вы хотите, чтобы перезагрузить ваше приключение, вы установите булево значение для истинного

если пользователь закончил установить логическое значение ean - false.

+0

Отклонитесь! Это очень помогает. – Bell 2010-12-17 03:15:15

Смежные вопросы