为什么我们不需要使用两个 ‘==’ 操作符来表示布尔变量的相等性?

huangapple go评论52阅读模式
英文:

Why don't we have to use two '=' operands for mentioning equality for boolean variable?

问题

当我在Java的while循环中编码时,我发现我们不必使用两个赋值操作符来表示仅对布尔变量的相等性进行赋值(我只找到这个情况)。这种情况背后的原因是什么?从现在开始谢谢。

`int a = 30;
boolean d = true;

while (a == 30) { <- 对于其他变量,我们需要像这样使用
}`

`int a = 30;
boolean d = true;

while (d == false) { <- 对于其他变量,我们需要像这样使用
}`

英文:

When I coding in a while loop in java , I discovered that we don't have to use two assignment operands for give meaning equality for JUST BOOLEAN VARİABLE(I found just it). What is the reason behind this situation? Thank you from now

` int a=30;
boolean d=true;

  while (a==30) {   &lt;- We need to use like that for other variables
       
	 
	}`

` int a=30;
boolean d=true;

  while (d=false) {   &lt;- We need to use like that for other variables
       
	 
	}`

答案1

得分: 2

因为赋值会解析为被赋的值。这将d设为false(并且解析为false),因此while不会进入循环体。

while (d=false) {

而且对于boolean类型,你不需要任何=

while (!d) {

或者

while (d) {

都是正确的,不涉及赋值。

英文:

Because assignment resolves to the assigned value. That sets d to false (and evaluates to false) and thus the while does not enter the loop body.

while (d=false) {

And you don't need any = for boolean(s).

while (!d) {

or

while (d) {

are correct, and don't involve assignment.

答案2

得分: 0

如果您真正使用两个"="运算符(而不是操作数),您将获得编译器错误...

"="是赋值运算符,"=="是相等运算符,而"= ="是语法错误。

如何使用它在此答案中有解释。

英文:

If you really use two "=" operators (not operands), you would get a compiler error …

"=" is the operator for assignments, "==" is the equality operator, and "= =" is a syntax error.

How to use it is explained in this answer.

huangapple
  • 本文由 发表于 2023年6月16日 00:14:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/76483611.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定