在“if”中与==和=混淆。声明 [英] Getting confused with == and = in "if" statement
问题描述
我知道我们不能在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) { }
推荐答案
因为赋值的结果是赋值的值。 ..所以在第二种情况下它仍然是一个 boolean
表达式。 如果
表达式要求条件为 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) { }
编译但不是第一个?
这是不直接与true和false进行比较的一个原因。所以我总是只写 if(b)
而不是 if(b == true)
和 if(!b)
而不是 if(b == false)
。当 b
和 c
if / code>是
boolean
变量,不可否认 - 一个拼写错误可能会导致问题。
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
循环等,只要整体条件表达式 boolean
。例如,您可能有:
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屋!