测验游戏 - IF语句&可能还有吗?

时间:2013-08-24 13:06:17

标签: java if-statement design-decisions

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

目前的代码是:

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

1 个答案:

答案 0 :(得分:1)

你的代码中似乎有一对额外的括号(在最初的if语句之后。你可能想要删除它们。另外,你可能想要添加一个else if。所以,像:< / p>

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

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