【问题标题】:Why is this boolean variable assigned true?为什么这个布尔变量被赋值为真?
【发布时间】:2016-04-02 06:48:07
【问题描述】:

我有以下两个产生不同输出的代码 sn-ps:

boolean a = false, b = false, c = false, d = false;
if (a = false | (b = false) || (c = true) | (d = true)){

}
System.out.println("if (a = false | (b = false) || (c = true) | (d = true))");
System.out.printf("a=%b\nb=%b\nc=%b\nd=%b\n\n", a, b, c, d);


if ((a = false) | (b = false) || (c = true) | (d = true)){

}
System.out.println("if ((a = false) | (b = false) || (c = true) | (d = true))");
System.out.printf("a=%b\nb=%b\nc=%b\nd=%b\n", a, b, c, d);

运行上述代码时,我得到以下输出:

if (a = false | (b = false) || (c = true) | (d = true))
a=true
b=false
c=true
d=true

if ((a = false) | (b = false) || (c = true) | (d = true))
a=false
b=false
c=true
d=true

请注意a 在第一个sn-p 中被分配true,但不是在第二个sn-p 中。

为什么将a 的赋值括在括号中会产生如此大的不同?

请注意,我有意使用赋值运算符 (=) 而不是比较运算符 (==)。

【问题讨论】:

  • @Eran 我不想比较,我将其设置为 false。但为什么会变成真的?
  • @JohnE.:那你到底为什么要使用 if 语句?
  • @Stultuske if 语句中的赋值没有错。
  • @luk2302 我没有混淆它,我正在分配它。
  • @JohnE.: 把你的内衣当帽子没什么问题。你也这样做吗?如果没有条件,为什么还要使用 if 语句?

标签: java assignment-operator operator-precedence boolean-expression


【解决方案1】:

不同之处在于,在第二种情况下,您直接分配(a = false) - 因此a 将是错误的。

在第一种情况下,您实际分配给 a 的值不是 false,而是

false | (b = false) || (c = true) | (d = true)

相当于

false | false || true | true

这是true。

看看operator precedence,看看这里到底发生了什么:

  • 首先处理|
  • 然后||
  • 然后=

因此该语句的计算方式如下:

a = false | (b = false) || (c = true) | (d = true)
a = false | false || true | true
a = true || false
a = true

【讨论】:

    【解决方案2】:

    如您所见here,| 运算符的优先级高于赋值运算符=。因此,当您不将 (a = false) 括在括号中时:

    if (a = false | (b = false) || (c = true) | (d = true))
    

    等价于

    if (a = (false | (b = false) || (c = true) | (d = true)))
    

    所以您将true 分配给a。

    另一方面,在

    if ((a = false) | (b = false) || (c = true) | (d = true))
    

    您将false 分配给a。

    【讨论】:

      猜你喜欢
      • 2020-02-01
      • 1970-01-01
      • 2023-03-04
      • 2012-08-21
      • 1970-01-01
      • 2022-12-09
      • 1970-01-01
      • 2020-07-30
      • 2018-08-06
      相关资源
      最近更新 更多