Is the String returned by JOptionPane.showInputDialog()
different from a regular String? When I try to compare it with "2"
, it returns false and go to the else block.
// Prompt user for the month
String monthString = JOptionPane.showInputDialog(
"Enter which month are you looking for: ");
// SMALL Months, ie: 2, 4, 6, 9, 11
else {
// Special case on February
if (monthString == "2" && isLeap)
result += "29 days!";
else if (monthString == "2")
result += "28 days!";
// Everytime my code to go to this block instead
else
result += "30 days!";
}
Only work if I parse month to Int and then compare it with literal 2. Why do my original version does not work?
int month = Integer.parseInt(monthString);
if (month == 2 && isLeap) ...
Use equals to compare string and not ==
Change this:
monthString == "2"
to
"2".equals(monthString)
in your if blocks
Equals compare the string contents while == compares the object equality. Read more from the related post here:
Also note the reverse comparision "2" against the monthStirng. This will prevent null pointer exception in case monthString is null.