繁体   English   中英

如何检查Java中的所有布尔值是真还是假?

[英]How to check if all boolean are true or false in Java?

我试图弄清楚如何检查三个变量是全部为真还是全部为假。 因此,当这些变量具有相同的值时,条件变为真;当它们不具有相同的值时,条件变为假。 我认为像(d == e == f)这样的东西会在这里帮助我,但只有当所有变量都设置为 true 时,条件才为 true。 但是当它们设置为 false 时,条件不起作用。 谁能向我解释为什么? 我知道一个非常基本的问题,但我自己真的无法弄清楚。

你可以这样尝试:

if((d && e && f) || (!d && !e && !f))

它将进入循环,要么全部为真,要么全部为假。

这是因为所有具有关系运算符的表达式都返回布尔值。

因此,首先评估 e == f。 由于这两个都是假的(两个运算符具有相同的值),所以这个表达式返回真值。 这个真值是根据 d 来评估的,而 d 是假的。 因此该表达式返回 false(因为两个运算符现在具有不同的值)。

要知道这3个变量是全真还是全假; 这是你可以做的:

boolean allTrue, allFalse;

if(a && b && c) allTrue = true;  //a, b & c will evaluate to boolean and if all three vars are true the condition will be true and hence the if statement will be accessed
if(!a && !b && !c) allFalse = true; //if the not of the 3 is true, i.e (the 3 boolean vars are false), the whole condtion will be true and the if-statement will be accessed and the allFalse will be set to true means all 3 are false
boolean allTrue=false;
boolean allFalse=false;

boolean a,b,c;//your three variables
if(a && b && c)
{allTrue=true;}
else if(!a && !b && !c)
 {allFalse=true;}

试试这个,这里我有两个变量标志,它们最初设置为 false,当其中一个条件为 true 时,只有它会被设置为 true,所以在最后一行代码之后,您可以检查 allFalse 或 allTrue 的值是否为 true 或 false .

先分别想一下条件:

boolean allTrue = a && b && c;
boolean allFalse = !(a||b||c);

然后组合它们:

boolean eitherAllTrueOrAllFalse = allTrue|allFalse;

应该可以像这样更接近原始公式:

boolean eitherAllTrueOrAllFalse = (d == e) && (d == f)

如果你只需要知道是真还是假,那么这已经绰绰有余了:

boolean flagAllTrue = a && b && c;

无需使用if else

让总和 = 0;

总和 += 一个? 1:0; 总和 += b ? 1:0; 总和 += c ? 1:0;

让 allTrueOrAllFalse = ( sum === 0 || sum === 3 );

暂无
暂无

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

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