java中的if条件
下面给出的 If
逻辑在 C 语言中运行良好,但在 java 中不起作用....为什么..??
编译时java会报错。
class test
{
public static void main(String[] args)
{
int i;
if(i=4)
System.out.println("hello");
}
}
If
logic given below works well in C language but it doesn't work in java....Why..??
It gives an error in java while compiling.
class test
{
public static void main(String[] args)
{
int i;
if(i=4)
System.out.println("hello");
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您需要在 if 语句中使用比较运算符 (
==
) 而不是赋值运算符 (=
)。在 C 中,有效赋值运算符的结果是分配的值。如果您的示例是用 C 语言编写的,则生成的代码将相当于
if(4)
,它的计算结果为 true 语句,并且代码始终会执行,编译器不会发出任何抱怨。 Java 会检查一些您可能指的是其他情况的情况,例如本例。You need to use the comparison operator (
==
) instead of the assignment operator (=
) in your if statement.In C, the result of a valid assignment operator is the value that is assigned. If your example was in C, the resultant code would be equivalent to
if(4)
, which evaluates to a true statement, and the code is always executed without any complaints by the compiler. Java checks for a few cases where you probably mean something else, such as this one.在 C/C++ 中,任何非零值都被视为 true,零被视为 false。也就是说,int 和 bool 是可以互换的。因此
if (i = 4)
在 C/C++ 中为 true。由于i
获取的值为 4,这相当于if (4)
。但在Java中,boolean与int不同,在需要boolean的地方不能使用int。请注意,i == 4
是布尔值,但i = 4
是 int。最后一项作业,不进行比较。In C/C++ any non-zero value is considered as true, zero considered false. That is, int and bool are interchangeable. So
if (i = 4)
is true in C/C++. Asi
is getting the value 4 and this is equivalent toif (4)
. But in Java boolean is different from int and you can not use int where boolean is required. Note then,i == 4
is boolean buti = 4
is int. The last one assignment, not compare.我不同意它在 C 中运行良好。它令人困惑,即使它确实可以编译。
这也会在 C 中打印“hello”,
这就是为什么在 Java 中不允许这样做。你必须写出
最接近这个问题的是使用布尔类型。
这可以编译,但几乎可以肯定是一个错误。
最常用的一个地方是阅读文本行
I would not agree that it works well in C. Its confusing, even if it does compile.
This will also print "hello" in C
Which is why it is not allowed in Java. You have to write
The closest you can get to this is problem is using the boolean type.
This compiles, but is almost certainly a bug.
One place assignment is commonly used is in reading lines of text
注意双等号
==
Note the double equal sign
==
它将在 C 中编译,因为 C 中的条件和 if 语句可以是 int 类型。但是,在您的条件下将 4 分配给 i ,它也不会执行您期望在 C 中执行的操作。
It will compile in C because the condition of and if statement in C can be of type int. However, you assign 4 to
i
in your condition, and it will not do what you expect it to do in C either.可以在 C 中工作,但不会做你期望的事情。事实上它会检查 i 是否非 0。
Java 强制您使用一个计算结果为布尔值的表达式。因此您需要 == 运算符。在这种情况下,赋值运算符的计算结果将是 int。
will work in C but will not do what you expect. It will in fact check that i is non-0.
Java forces you to have an expression that evaluates to a boolean. Hence you need the == operator. The assignment operator in that case will evaluate to int.