用户提示使用if语句

时间:2013-05-11 00:00:28

标签: java

我正在尝试编写一个程序,询问用户是否怀孕了。我遇到的问题是,如果此人输入“可能”或任何其他响应而不是“是”或“否”,我希望程序说“这是一个是或否”,然后提示用户再次回答问题。相反,它打印“这是一个是或否的问题”和“你怀孕吗?”但它不能接受另一个回应。这是我正在尝试做的正确格式吗?换句话说,我希望我的程序不断询问用户她是否怀孕,直到我得到是或否答案。

import acm.program.*;

public class AskProgram extends ConsoleProgram{
    public void run(){

        String answer = readLine(" are you pregnant? ");

        if (answer.equals("yes")) {
            println("Great! Congratulations ");
        } else if (answer.equals("no")) {
            println("keep trying it will happen."); 
        } else {
            println("Its a yes or no question");
            readline("are you pregnant? ");
        }          
    }
}

2 个答案:

答案 0 :(得分:4)

这将重复该块,直到用户输入“是”或“否”:

String answer = "";
while (!answer.equalsIgnoreCase("yes") && !answer.equalsIgnoreCase("no")) {
    answer = readLine("Are you pregnant?");
    if (answer.equalsIgnoreCase("yes")) {
        println("Great! Congratulations ");
        break;
    } else if (answer.equalsIgnoreCase("no")) {
        println("keep trying it will happen."); 
        break;
    } else {
        println("Its a yes or no question");
        readline("are you pregnant? ");
    }    
}

答案 1 :(得分:-1)

这是一个使用递归(和返回值)的版本:

private static boolean isPregnant() {
    String answer = readLine("Are you pregnant?");
    if (answer.equalsIgnoreCase("yes")) {
        println("Great! Congratulations ");
        return true;
    } else if (answer.equalsIgnoreCase("no")) {
        println("keep trying it will happen.");
        return false;
    } else {
        println("It's a yes or no question");
        return isPregnant();
    }

}