JOptionPane.showInputDialog()返回的字符串是否不同于常规字符串?当我尝试将其与"2"进行比较时,它返回false并转到else块。

        // 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!";
        }


仅当我将月份解析为Int然后将其与文字2进行比较时才起作用。为什么我的原始版本不起作用?

int month = Integer.parseInt(monthString);
if (month == 2 && isLeap) ...

最佳答案

使用等于来比较字符串而不是==

更改此:

monthString == "2"




"2".equals(monthString)


在你的if块中

等于比较字符串内容,而==比较对象相等性。在此处阅读相关文章的更多信息:

Java String.equals versus ==

还要注意与monthStirng的反向比较“ 2”。如果monthString为null,这将防止null指针异常。

10-07 15:30