Long story short, the snippets below is about converting the texted month to numbered month (ex, Jan -> 1). There’s no error but in the end I keep getting 0 as the result of m. Where’s the problem?
//date1s[] is the result of splitting date1 by spaces (date1 = 1 Jan 2012)
m = convertMonth(date1s[1]); //date1s[1] contains the Month; date1s[0] the date and date1s[2] the year
public int convertMonth(String monw) {
int x = 0;
if (monw == "Jan") {
x = 1;
}
else if (monw == "Feb") {
x = 2;
}
else if (monw == "Mar") {
x = 3;
}
else if (monw == "Apr") {
x = 4;
}
else if (monw == "May") {
x = 5;
}
else if (monw == "Jun") {
x = 6;
}
else if (monw == "Jul") {
x = 7;
}
else if (monw == "Aug") {
x = 8;
}
else if (monw == "Sep") {
x = 9;
}
else if (monw == "Oct") {
x = 10;
}
else if (monw == "Nov") {
x = 11;
}
else if (monw == "Dec") {
x = 12;
}
return x;
}
Use the
.equals()method of String.if (monw.equals("Jan"))When you use
==operator, it compares the memory locations of the two objects and returnsfalse. In other words, it only returnstrueif the same object is on both sides of equation. So you should use the.equals()method instead, which returnstrueif two different objects have the same value.EDIT:
I just checked, @LazyCubicleMonkey is right. The
==operator checks if locations in memory are the same. I created a class, overrided thehashCode()method, created two objects and printedobj1==obj2. It printsfalse.