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

时间:2016-10-30 09:57:47

标签: java operators

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

7 个答案:

答案 0 :(得分:5)

您可以尝试这样:

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

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

答案 1 :(得分:2)

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

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

答案 2 :(得分:1)

知道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

答案 3 :(得分:0)

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所以在最后一行代码之后你可以检查allFalse或allTrue是否有值是真还是假。

答案 4 :(得分:0)

如果你只需要知道所有的都是真的或者都是假的,那么这就足够了:

boolean flagAllTrue = a && b && c;

无需使用 if else

答案 5 :(得分:0)

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

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

答案 6 :(得分:-1)

首先分别考虑条件:

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

然后结合它们:

boolean eitherAllTrueOrAllFalse = allTrue|allFalse;
相关问题