2013-05-11 53 views
3

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

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

将代码放在'while'循环中,将退出条件设置为yes或no的答案 – Reimeus 2013-05-11 00:02:49

回答

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

+1在我发布我的代码之前+1没有看到您的答案,请删除我的代码。 – 2013-05-11 00:05:52

+0

@ Alex23是一个while循环的唯一方式可以做到? if语句可以完成吗? – 2013-05-11 00:06:29

+1

@JessicaM。它会转到,这是非常丑陋的/不可读的,并在java中存在。 – 2013-05-11 00:07:40

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

} 
+0

@Downvoter:关心评论? – 2013-05-11 00:31:00

+0

这个函数应该真的返回一个布尔值或一个字符串来表示结果是什么! (我没有downvote顺便说一句)。 – 2013-05-11 00:35:55

+0

我会改变的唯一的其他事情,我不会在这个函数中打印“很好......”或“继续尝试...”字符串 - 应该在调用这个函数的函数中完成。这样你可以稍后重新使用这个函数,如果你需要并且不想打印这些字符串,如果你知道我的意思:) – 2013-05-11 00:42:58