我有点难以理解 ! ||和 && 当它们在 while 条件下被测试时。在下面的例子中,我想让程序问一个问题“你在屏幕上看到一个四吗?”然后,如果此人回答“否”,程序将继续并继续询问。如果用户输入答案"is",程序将退出,但我的不会。
在我的 while 循环条件下,我是否告诉 while 循环仅在 i 小于 5 且问题的答案不是"is"时才继续?怎样才是正确的思考方式! ||和 && 何时在 while 循环的上下文中使用?
import acm.program.*;
public class WhileConditionTestProgram extends ConsoleProgram{
public void run(){
String question = ("do you see a four on the screen? ");
int i = 1;
while(i <= 20 && !(question.equals("yes"))){
String question = readLine("do you see a 4 on the screen?: ");
i++;
}
}
}
最佳答案
除了明显的变量重新声明问题外,您还应该考虑使用 do-while
循环,因为您至少要读取一次用户输入。
因此,您可以更好地将循环更改为:
int i = 0;
String answer = "";
do {
answer = readLine("do you see a 4 on the screen?: ");
i++;
} while (i <= 20 && !answer.equalsIgnoreCase("yes"));
注意:我使用 equalsIgnoreCase
只是为了安全起见,因为您正在读取用户的输入。你永远不知道它传递的是什么字母组合。
关于java - 使用 ! 测试 while 条件的真/假||和 && 运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17458798/