我实际上尝试将四个不同的 boolean 值转换为 true/false。
我的情况是,
True false false false Then true else false
false True false false Then true else false
false false True false Then true else false
false false false True Then true else false
我试过这样,
int a=1;
int b=0;
int c=0;
int d=0;
int cnt=0;
// A block of code will be executed only when any one of the four variables is 1 and
//the rest of them is 0. and another block will be executed when the above mentioned
//condition become false.
if (a==0) { cnt+=1; }
if (b==0) { cnt+=1; }
if (c==0) { cnt+=1; }
if (d==0) { cnt+=1; }
if (cnt==3) { // true block } else { //false block }
上面的代码工作得很好,但我接受了一个挑战,在一个 if 语句中检查这个条件。然后我就这样试了。
if(!((!(a==0) && !(b==0)) && (!(c==0) && !(d==0))))
{
//true block
}
else
{
//false block
}
上述条件在某些组合中失败(a=1 b=0 c=1 d=1)。谁能指出问题所在。?或提出任何新想法。?
My objective is convert (3 false + 1 true) into true other wise into false.
[注意:我给出的场景只是为了理解目的。 a、b、c、d 值可能不同。看我的目标。不要说支持 1 和 0 的答案]
最佳答案
我想我会使用以下方法,它使算法可重用并支持任意数量的参数。仅当只有一个参数为真时,它才返回真。
private boolean oneTrue(boolean... args){
boolean found = false;
for (boolean arg : args) {
if(found && arg){
return false;
}
found |= arg;
}
return found;
}
你可以这样测试:
private void test(){
boolean a = false;
boolean b = true;
boolean c = false;
boolean d = false;
System.out.println(oneTrue(a,b,c,d));
}
关于java - 将 boolean 值的四个组合转换为真/假 - 使用 IF Else 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18481244/