java - 将 boolean 值的四个组合转换为真/假 - 使用 IF Else 语句

标签 java algorithm if-statement boolean-operations

我实际上尝试将四个不同的 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/

相关文章:

algorithm - TTTD分块算法中使用的哈希函数?

python - 如何使这个 Python 代码块简短而高效

java - 如何在TestNG中实现single Threaded=true

java - Java 中的 Koblitz 方法

algorithm - 时间复杂度和操作的元素数量

algorithm - 通过每次从 N 个列表中选择一个数字来从 N 个列表中找到第 k 个最大数字的高效算法

Java:一元 if - npe

java - android java switch 语句中缺少或删除循环周期

java - 我尝试在 Ubuntu 20.04 中的 eclipse 中创建一个新项目,但它给了我这个错误 Errors generated during the build

java - 在 Java 中使用 Collectors.toMap 时,如何跳过向新 map 添加条目?