1

我对此很陌生,想知道是否有人可以帮助我。我希望代码能够在某些问题得到答案后停止提问。我让它在鹦鹉和鸸鹋等第一个上工作,但我似乎无法添加其他人。请告诉我我做错了什么。

到目前为止的代码是:

import java.util.Scanner;

/**
* Guessing Game.
* 
* @author O 
* @version 99
*/
public class Quiz
{
public static void main(String[] args)
{
    Scanner keyboard = new Scanner(System.in);
    boolean answerIsCorrect;

    System.out.println("Think of an animal.\n");

    if(ask("Is it a bird? ", keyboard))
    {
        if(ask("Can it fly? ", keyboard))
        {
            answerIsCorrect = ask("Is it a parrot? ", keyboard);
        }
        else
        {
            answerIsCorrect = ask("Is it an emu? ", keyboard);
        }

    {
        if(ask("Does it live in the ocean? ", keyboard))
    {
        if(ask("Is it a whale? ", keyboard))
        {
            answerIsCorrect = ask("Answer 1? ", keyboard);
        }
        else
        {
            answerIsCorrect = ask("Answer 2? ", keyboard);
        }
    }
    }
    }



    else



    {
        if(ask("Does it lay eggs? ", keyboard))
        {
            answerIsCorrect = ask("Is it a platypus? ", keyboard);
        }
        else
        {
            answerIsCorrect = ask("Is it a kangaroo? ", keyboard);
        }
    }


    if(answerIsCorrect)
    {
        System.out.println("I am good!");
    }
    else
    {
        System.out.println("Drats! I guess I don't know then!");
    }
 }

 /**
 * A utility method to ask a yes/no question
 * 
 * @param question the question to ask
 * @param a scanner for user input
 * 
 * @return whether the user answered "yes" (actually, whether the user answered
   anything starting with Y or y)
 */
 private static boolean ask(String question, Scanner keyboard)
 {
    System.out.print(question);

    String answer = keyboard.nextLine().trim();



    return answer.charAt(0) == 'Y' || answer.charAt(0) == 'y';
  }
   }
4

1 回答 1

1

您的代码中似乎有一对额外的括号(在初始 if 语句之后。您可能想要删除它们。此外,您可能想要添加一个else if. 所以,类似于:

if(ask("Is it a bird? ", keyboard))
{
    if(ask("Can it fly? ", keyboard))
    {
        answerIsCorrect = ask("Is it a parrot? ", keyboard);
    }
    else
    {
        answerIsCorrect = ask("Is it an emu? ", keyboard);
    }           
}
else if(ask("Does it live in the ocean? ", keyboard))
{
    if(ask("Is it a whale? ", keyboard))
    {
        answerIsCorrect = ask("Answer 1? ", keyboard);
    }
    else
    {
        answerIsCorrect = ask("Answer 2? ", keyboard);
    }
}
else
{
    if(ask("Does it lay eggs? ", keyboard))
    {
        answerIsCorrect = ask("Is it a platypus? ", keyboard);
    }
    else
    {
        answerIsCorrect = ask("Is it a kangaroo? ", keyboard);
    }
}

希望有帮助。祝你学习如何编程好运。

于 2013-08-24T13:25:26.470 回答