java 为什么java需要双等号?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16577891/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 23:21:05  来源:igfitidea点击:

Why does java require a double equals sign?

java

提问by java

Why does java require a double equals sign (==) when comparing Integers in a ifstatement?

为什么java在if语句中比较整数时需要双等号(==)?

For example

例如

if(x = 3.141)
     System.out.println("x is equal to pi.");

is incorrect, it should be

不正确,应该是

if(x == 3.141)
     System.out.println("x is equal to pi.");

I know that "==" is used to compare integers and "=" is used to set an integer value, but why in a ifstatement does this remain true?

我知道“==”用于比较整数,“=”用于设置整数值,但为什么在if语句中这仍然为真?

Is it even allowed to assign a variable a value in an if statement(or initiate a new variable)?

甚至允许在if 语句中为变量赋值(或启动一个新变量)?

Is there any reason anyone would ever want to assign a variable a new value inside an ifstatement (if so please provide an example)?

是否有任何人想要在if语句中为变量分配一个新值(如果是,请提供示例)?

This seems like a question that should already have an answer, but I was unable to find one on here or using google, if this is a duplicate question please tell me and I will remove it immediately.

这似乎是一个应该已经有答案的问题,但我无法在这里或使用谷歌找到一个,如果这是一个重复的问题,请告诉我,我会立即将其删除。

回答by Thilo

Wouldn't it be confusing if =sometimes did assignment, and sometimes comparison, depending in which context you used it?

如果=有时进行赋值,有时进行比较,这取决于您在哪种上下文中使用它,这会不会令人困惑?

That sounds like a bad idea, and would introduce errors.

这听起来像一个坏主意,并且会引入错误。

Plus, the current syntax is compatible with C and C++, so a lot of people are familiar with it.

另外,当前的语法与 C 和 C++ 兼容,因此很多人都熟悉它。

Is there any reason anyone would ever want to assine a variable a new value inside of an if statement (if so please provide an example)?

是否有任何人想要在 if 语句中为变量赋值一个新值(如果是,请提供示例)?

It's quite common in whileloops:

这在while循环中很常见:

int b;
while ((b=in.read()) != -1){

回答by eyadMhanna

= 

is used for assignment.

用于赋值。

== 

is used for comparison.

用于比较。

Is it even allowed to assign a variable a value in an if statement (or initiate a new variable)?

甚至允许在 if 语句中为变量赋值(或启动一个新变量)?

yes it is allowed.

是的,这是允许的。

回答by user207421

History of programming languages 101:

编程语言的历史 101:

  • Fortran uses =for both.
  • Algol introduced :=for assignment and used =for comparison. This was required to resolve a grammar ambiguity.
  • Pascal followed suit.
  • PL/1 did not.
  • I can't speak for B or BCPL but by the time we got C it was =for assignment and ==for comparison, again to resolve a grammar ambiguity
  • C++ followed C
  • Java followed C++ in many respects including this one.
  • Fortran=用于两者。
  • 引入 Algol:=用于赋值并用于=比较。这是解决语法歧义所必需的。
  • 帕斯卡紧随其后。
  • PL/1 没有。
  • 我不能说 B 或 BCPL,但是当我们得到 C 时,它是=为了分配和==比较,再次解决语法歧义
  • C++ 跟随 C
  • Java 在很多方面都遵循 C++,包括这一点。

The grammar ambiguity arises because of allowing assignments in expressions. Contrary to your assertion, if (x = true)is legal in Java if xis of type boolean.

语法歧义是因为允许在表达式中赋值。与您的断言相反,如果是 boolean 类型if (x = true)则在 Java 中是合法的。x

回答by Bohemian

==is the identity comparator, which works for both objects and primitives. It answers the question "are the two things the samething".

==是标识比较器,它适用于对象和基元。它回答了“这两件事一回事吗”的问题。

=is the assignment operator. It sets the value of the left side to the right side.

=是赋值运算符。它将左侧的值设置为右侧。

Things can turn buggy when using your example with booleans:

将您的示例与布尔值一起使用时,事情可能会变得有问题:

boolean b;

if (b = true) // This compiles, but is a bug, because it sets b, not tests it

While other types won't compile with this syntax, booleanand Booleando, so that's why the following pattern is advised:

而其他类型不会有这种语法编译,boolean并且Boolean做的,所以这就是为什么以下模式建议:

if (b)

回答by zw324

Note what error message you get for if (x = 3.141); it is a type error(cannot convert from doubleto boolean).

请注意您收到的错误消息if (x = 3.141);这是一个类型错误(无法从doubleto转换boolean)。

The assignment's type is the type of its both sides; if the type of the assignment is boolean (if (x = true), or even if (x = a.equals(b))), then it is legal to write.

赋值的类型为其双方的类型;如果赋值的类型是 boolean ( if (x = true), or even if (x = a.equals(b))),那么写是合法的。

So since it is legal to assign a value to a booleanin the condition, you'd have to use ==for comparison.

因此,由于boolean在条件中为 a 赋值是合法的,因此您必须使用它==进行比较。

回答by Jeanne Boyarsky

Is it even allowed to assine a variable a value in an if statement (or initiate a new variable)?

是否甚至允许在 if 语句中为变量赋值(或启动一个新变量)?

Yes. A common idiom for doing this is:

是的。这样做的一个常见习语是:

String line = null;
while ( (line = in.readLine()) != null ) {
  // do work
}

In the loop, line is assigned a value and then compared to null. I can't think of an example with ints; it certainly wouldn't be clear there.

在循环中, line 被分配一个值,然后与 null 进行比较。我想不出一个带有整数的例子;那里肯定不清楚。

回答by ben schwartz

you can absolutely assign a variable in an if statement. also, that's just the way it works: =always is assignment, and ==is always comparison.

您绝对可以在 if 语句中分配变量。而且,这就是它的工作方式:=总是赋值,==总是比较。

回答by coolcfan

So..

所以..

=is assignment, and ==is comparison, and it is always like this, no matter where they are used.

=是赋值,==也是比较,不管用在什么地方,总是这样。

And assignment is different with "declaration". An assignment statement has its return value, while a declaration doesn't. So you can't write boolean a = falsein the ()of if statement, but you can write a = falsewhen a has been declared before.

而赋值与“声明”不同。赋值语句有它的返回值,而声明没有。所以你不能boolean a = false()of if语句中写,但是你可以a = false在a之前声明过的时候写。

Not all assignments are legal. For example:

并非所有的分配都是合法的。例如:

int index;
if (index = str.indexOf("something")) {
    ...
}

It's not legal, because String.indexOf(String)returns an int, while ifrequires a boolean.

这是不合法的,因为String.indexOf(String)返回一个整数,而if需要一个布尔值。

Also, there is a huge difference between "legal"and "making sense".

此外,“合法”“有意义”之间也存在巨大差异。

int index;
if ((index = str.indexOf("something")) != -1) {
    ...
}

It is legal, as !=operation returns a boolean, and it makes sense, as I do want to check if the str contains a substring "something";

这是合法的,因为!=操作返回一个布尔值,这是有道理的,因为我确实想检查 str 是否包含子字符串“某物”;

However,

然而,

int index;
boolean flag;
if ( flag = ((index = str.indexOf("something")) != -1) ) {
    ...
}

is also legal, as the statement as last returns a boolean; but it DOESN'T make sense, because the !=statement already returns a boolean.

也是合法的,因为 last 语句返回一个布尔值;但它没有意义,因为该!=语句已经返回一个布尔值。