【问题标题】:Boolean operator which gives true from two similar values布尔运算符,从两个相似的值中得出真值
【发布时间】:2021-01-20 23:46:27
【问题描述】:

给定两个布尔变量 x 和 y,运算符应该是这样的

boolean getResult(boolean x, boolean y) {
    return x op y;
}

以下断言通过

assertEquals(getResult(true, true), true);
assertEquals(getResult(false, false), true);
assertEquals(getResult(true, false), false);
assertEquals(getResult(false, true), false);

有这方面的运营商吗?

编辑。

抱歉,我没有提到除相等检查之外的运算符。我正在寻找某种可以像我们在一般逻辑门中一样给出组合结果的操作。我只是想知道它是否可能。如果可能的话,操作是什么。

【问题讨论】:

  • 我很困惑,您希望它随机返回 true 还是 false?
  • @Luke 这根本不是随机的。如果两个参数相同,则仅返回true,否则返回false。完全确定。
  • 是的。我想我错过了除平等检查之外的其他内容。某种可以给出组合结果的操作,就像我们在一般逻辑门中所做的那样。

标签: java boolean boolean-logic


【解决方案1】:

你只需要检查两个值是否相等。

boolean getResult(boolean x, boolean y) {
 return x === y;
}

【讨论】:

  • 抱歉,我已经编辑了帖子以包含缺失的细节。
  • ok :) 您可以使用@Arvind 的答案中提到的替代方式来完成
【解决方案2】:

有这方面的运营商吗?

是的,这个操作符可以是==

检查下面给出的解释:

true == true => true
false == false => true
true == false => false
false == true => false

演示:

public class Main {
    public static void main(String[] args) {
        // Test
        System.out.println(getResult(true, true));
        System.out.println(getResult(false, false));
        System.out.println(getResult(true, false));
        System.out.println(getResult(false, true));
    }

    static boolean getResult(boolean x, boolean y) {
        return x == y;
    }
}

输出:

true
true
false
false

或者,您可以通过否定bitwise exclusive OR 操作得到相同的结果,如下所示:

public class Main {
    public static void main(String[] args) {
        // Test
        System.out.println(getResult(true, true));
        System.out.println(getResult(false, false));
        System.out.println(getResult(true, false));
        System.out.println(getResult(false, true));
    }

    static boolean getResult(boolean x, boolean y) {
        return !(x ^ y);
    }
}

输出:

true
true
false
false

【讨论】:

  • 抱歉,我已经编辑了帖子以包含缺失的细节。
  • @xploreraj - 我添加了另一种方法来获得相同的结果。
猜你喜欢
  • 1970-01-01
  • 2013-03-02
  • 2012-09-20
  • 1970-01-01
  • 2013-07-07
  • 1970-01-01
  • 2011-01-23
  • 2012-02-19
  • 2016-02-24
相关资源
最近更新 更多