3

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

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? ");
        }          
    }
}
4

2 回答 2

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? ");
    }    
}
于 2013-05-11T00:04:04.847 回答
-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();
    }

}
于 2013-05-11T00:13:31.777 回答