Why doesn#39;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
返回 1
时打印正确的消息.
What I want to achieve is printing proper message if and only if compareTo
returns 1
.
推荐答案
你应该比较 (==
) 而不是赋值 (=
).这可能非常危险!为了避免这种情况,你可以使用 Yoda notation
所以而不是比较
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 中不能正常工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么我使用 =(单个等号)进行的等式比较在 Java 中不能正常工作?
基础教程推荐
- 如何使用 Java 创建 X509 证书? 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- 降序排序:Java Map 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01