java if语句错误
在我看来,这个 if
语句不起作用。
我是java新手,但我很了解C#和C++,但我以前从未见过这样的事情:
today=edit[0].substring(0,10);
if (today == edit[0].substring(0,10))
{
pars_prog.addView(name_prog[i]);
}
而且它没有进入IF
函数?
Java (Android) 中的 if 语句有何不同?
It seems to me that this if
statement is not working.
I'm new in java, but i know C# and C++ pretty well, but I've never seen such a thing before:
today=edit[0].substring(0,10);
if (today == edit[0].substring(0,10))
{
pars_prog.addView(name_prog[i]);
}
And it doesn't get into the IF
function?
Are if statements different in Java (Android)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
当您对任何对象引用(无论是字符串还是任何其他非原始类型)使用
==
时,它只是比较引用是否相等 - 即它们是否引用了确切的对象相同的对象,或者它们是否都为空。在本例中,您想要确定字符串是否相等 - 即它们是否表示相同的字符序列。为此,您应该使用
equals
方法:但是,通常在执行此操作时,您应该小心
equals
调用的目标为非空,否则您将得到一个NullPointerException
。请注意,C# 是相似 - 除了
==
运算符可以重载,并且对于字符串
是重载的。如果操作数的编译时类型不都是string
,您仍然会得到引用比较:When you use
==
for any object references (whether strings or any other non-primitive type) it simply compares whether the references are equal - i.e. whether they refer to the exact same object, or whether they're both null.In this case, you want to determine whether the strings are equal - i.e. whether they represent the same sequence of characters. You should use the
equals
method for that:However, in general when doing this you should be careful that the target of the
equals
call is non-null, or you'll get aNullPointerException
.Note that C# is similar - except that the
==
operator can be overloaded, and is overloaded forstring
. If the compile-time types of the operands aren't bothstring
, you'll still get reference comparison:您正在尝试将字符串与
==
进行比较,这是身份比较 - 它将检查两个实例是否相同(在 JVM 中),而不是比较它们的内容。请改用
today.equals(..)
。也就是说,如果您正在处理日期,那么
String
并不是处理此问题的最佳方法。使用Calendar
、Date
(有点过时)或joda-timeDateTime
You are trying to compare strings with
==
, which is identity comparison - it will check if the two are the same instance (in the JVM) rather than comparing their contents.Use
today.equals(..)
instead.That said, if appears you are working with dates, so a
String
is not the best way to handle this. UseCalendar
,Date
(a bit obsolete) or joda-timeDateTime
比较字符串时必须使用 equals 方法。现在您正在比较引用,这就是为什么您从不输入 if 块
You have to use the equals method when comparing strings.. Right now you are comparing references and thats why you never enter the if block