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

到目前为止的代码是:

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';
  }
   }

最佳答案

您的代码中似乎还有一对括号(在初始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);
    }
}


希望能有所帮助。学习如何编程,祝您好运。

关于java - 测验游戏-IF陈述和其他可能陈述?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18418918/

10-11 03:52