0

这是我的问题,当我没有在 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);
4

1 回答 1

3

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

错误的:

if (str == "foo") {

}

正确的:

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

}
于 2013-05-01T03:33:50.990 回答