简体   繁体   English

同时循环测试条件

[英]While loop testing condition

I'm trying to execute while loop until the user enter Yes or No. 我正在尝试执行while循环,直到用户输入Yes或No.

Why can't there be an OR in the testing function instead of AND? 为什么测试函数中没有OR而不是AND?

While using OR, it can be either yes or no . 使用OR时,它可以是yesno

System.out.print("Enter yes or no: ");
String answer = input.getNext();
while (!answer.equals("yes") && !answer.equals("no")) {
    System.out.println("Enter ONLY yes or no, please: ");
    answer = input.getNext();
}
System.out.println("Thank you!");

Because !answer.equals("yes") && !answer.equals("no") basically says while answer is not "yes" and answer is not "no". 因为!answer.equals("yes") && !answer.equals("no")基本上说虽然answer不是“是”而answer不是“不”。

In order to make it an OR you can do it like: 为了使它成为OR你可以这样做:

while(!(answer.equals("yes") || answer.equals("no")))
{
}

Which means, while the following condition is not true; 这意味着,虽然以下条件不属实; condition: answer is "yes" or answer is "no" 条件: answer是“是”或answer是“否”

while (!answer.equals("yes") && !answer.equals("no")) means that the loop terminates when the condition becomes false. while (!answer.equals("yes") && !answer.equals("no"))表示当条件变为false时循环终止。 According to de Morgan laws, !(!answer.equals("yes") && !answer.equals("no")) is answer.equals("yes") || answer.equals("no") 根据de Morgan定律, !(!answer.equals("yes") && !answer.equals("no"))answer.equals("yes") || answer.equals("no") answer.equals("yes") || answer.equals("no") . answer.equals("yes") || answer.equals("no") That is, the loop terminates when the answer is either "yes" or "no" - that's exactly what you want. 也就是说,当答案要么是 “是”或“否”的循环终止-这正是你想要的。

If you change && to || 如果您将&&更改为|| , the loop would terminate when the answer is both "yes" and "no" at the same time, which is impossible. ,当答案同时为 “是”和“否”时,循环将终止,这是不可能的。

If you use the short circuit or/and (|| and &&) the system doesn't evaluate the entire expression if it doesn't have to. 如果使用短路或/和(||和&&),系统不会评估整个表达式(如果不需要)。 So if the user enters "no", the first part that checks if it is not "yes" evaluates to true. 因此,如果用户输入“no”,则检查它是否为“yes”的第一部分的计算结果为true。 Since an or condition only needs one true to evaluate to true it doesn't evaluate anything else and just returns. 由于一个或条件只需要一个true来评估为true,因此它不会评估任何其他内容而只返回。

You need && because you are saying if the answer is not yes and is not no ask for input again. 你需要&&,因为你说的是​​答案是肯定的,而不是不再要求输入。 Here is more on short circuit boolean operators: https://users.drew.edu/bburd/JavaForDummies4/ShortCircuitEval.pdf . 以下是短路布尔运算符: https//users.drew.edu/bburd/JavaForDummies4/ShortCircuitEval.pdf

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM