if语句不检查条件

时间:2013-05-01 03:31:01

标签: java if-statement

这是我的问题,当我没有在inputdialog中插入任何内容时if语句没有显示messagedialog,但是当我使用!=来比较条件时,它会显示,为什么会这样?据我所知!=意思是不相等而且==相等

    String firstName = "";
    String lastName = "";

    firstName = JOptionPane.showInputDialog("Please enter your first name");

    if (firstName == "") {
        JOptionPane.showMessageDialog(null, "Don't leave it blank!");
    } else
    {
        lastName = JOptionPane.showInputDialog("Please enter your last name");
    }

    String msg = "Hello " + firstName + lastName + "!";
    JOptionPane.showMessageDialog(null, msg);

1 个答案:

答案 0 :(得分:3)

java中最常见的错误之一。字符串需要.equals()而不是==

错:

if (str == "foo") {

}

右:

if ("foo".equals(str)) { // done in this order to avoid NPE

}