与“if"中的 == 和 = 混淆;陈述 [英] Getting confused with == and = in "if" statement

查看:15
本文介绍了与“if"中的 == 和 = 混淆;陈述的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道我们不能在 java 的 if 语句中使用赋值运算符,就像我们在其他几种语言中使用的那样.

I know that we cant use assignment operator in if statements in java as we use in any other few languages.

就是

            int a;

            if(a = 1) {  } 

会出现编译错误.

但是下面的代码工作正常,如何?

but the following code works fine, how?

           boolean b;

           if(b = true) {   }

这是规则的例外,不能在 if 语句中使用赋值.

EDIT : Is this the exception to rule that assignment cant be used in if statement.

推荐答案

因为赋值的结果"就是赋值的值...所以在第二种情况下它仍然是一个 boolean 表达式.if 表达式要求条件是一个 boolean 表达式,它满足第二个但不满足第一个.实际上,您的两个片段是:

Because the "result" of an assignment is the value assigned... so it's still a boolean expression in the second case. if expressions require the condition to be a boolean expression, which is satisfied by the second but not the first. Effectively, your two snippets are:

int a;

a = 1;
if (a) { }

boolean b;

b = true;
if (b) { }

从那个扩展中是否清楚第二个版本可以编译但第一个版本不能编译?

Is it clear from that expansion that the second version will compile but not the first?

这是不直接与真假进行比较的原因之一.所以我总是只写 if (b) 而不是 if (b == true)if (!b) 而不是 if (b == false).当 bcboolean 变量时,你仍然会遇到 if (b == c) 的问题,诚然- 那里的拼写错误可能会导致问题.不过,我不能说它曾经发生在我身上.

This is one reason not to do comparisons with true and false directly. So I would always just write if (b) instead of if (b == true) and if (!b) instead of if (b == false). You still get into problems with if (b == c) when b and c are boolean variables, admittedly - a typo there can cause an issue. I can't say it's ever happened to me though.

响应您的编辑 - 可以在 if 语句和 while 循环等中使用各种赋值,只要整体条件表达式为 布尔值.例如,您可能有:

Responding to your edit - assignments of all kinds can be used in if statements - and while loops etc, so long as the overall condition expression is boolean. For example, you might have:

String line;
while ((line = reader.readLine()) != null)
{
    // Do something with a line
}

虽然我通常避免条件中的副作用,但这个特殊的习惯用法对于上面显示的示例或使用 InputStream.read 通常很有用.基本上是虽然我读到的值有用,但请使用它."

While I usually avoid side-effects in conditions, this particular idiom is often useful for the example shown above, or using InputStream.read. Basically it's "while the value I read is useful, use it."

这篇关于与“if"中的 == 和 = 混淆;陈述的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆