开发者

java if statement error

开发者 https://www.devze.com 2023-03-22 15:16 出处:网络
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:

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 (tod开发者_如何学Cay == 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)?


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:

if (today.equals(edit[0].substring(0,10)))

However, in general when doing this you should be careful that the target of the equals call is non-null, or you'll get a NullPointerException.

Note that C# is similar - except that the == operator can be overloaded, and is overloaded for string. If the compile-time types of the operands aren't both string, you'll still get reference comparison:

object text1 = new StringBuilder("hello").ToString();
object text2 = new StringBuilder("hello").ToString();
Console.WriteLine(text1 == text2); // False


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. Use Calendar, Date (a bit obsolete) or joda-time DateTime


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

0

精彩评论

暂无评论...
验证码 换一张
取 消