为什么我的等式比较使用=(单个等于)在Java中无法正常工作? [英] Why doesn't my equality comparison using = (a single equals) work correctly in Java?
本文介绍了为什么我的等式比较使用=(单个等于)在Java中无法正常工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在以下行中有语法错误。但是我无法理解这个错误的原因是什么。
I have a syntax error in the following line. However I can't understand what is the reason of this error.
if (address1.compareTo(address2) = 1)
System.out.println(address1 + " is greater than " + address2);
当且仅当 compareTo <时,我想要实现的是打印正确的消息/ code>返回
1
。
推荐答案
你应该比较( ==
)而不是分配( =
)。这可能非常危险!为了避免这种情况,您可以使用 Yoda表示法
,而不是比较
You should compare (==
) instead of assigning (=
). It can be very dangerous! To avoid such situations you can use Yoda notation
so instead of comparing
address1.compareTo(address2) == 1
您可以比较:
1 == address1.compareTo(address2)
如果缺少 =
,则会出现比较错误。
In case of missing =
, there will be comparation error.
在您的情况下,它会比较好:
In your case, it would be better to compare:
address1.compareTo(address2) > 0
这篇关于为什么我的等式比较使用=(单个等于)在Java中无法正常工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文