【问题标题】:Don't Understand why this does not work input string [duplicate]不明白为什么这不起作用输入字符串[重复]
【发布时间】:2018-02-25 00:03:54
【问题描述】:

对不起,我有一个简单的问题。我试图弄清楚为什么当用户在第一个提示输入动物然后在第二个提示输入是时程序不会打印出“你的项目是一只驼鹿”。任何帮助都会非常感谢

    public static void main(String[] args) {
    // TODO Auto-generated method stub


    String Answer1;
    String Answer2;

    // Read in how much cash the user has
    Answer1 = JOptionPane.showInputDialog("Question 1: Is it an animal, vegetable, or mineral");
    Answer2 = JOptionPane.showInputDialog("Question 2: Is it bigger than a breadbox");


    if (Answer1 == "animal" && Answer2 == "yes") {
        JOptionPane.showMessageDialog(null, "Your item is: A Moose");
    }
}

}

【问题讨论】:

  • 查看 String.equals 的 Javadoc。您不能使用 == 运算符比较字符串内容。

标签: java string input joptionpane


【解决方案1】:

在 Java 中,您不会将字符串与双等号进行比较,它仅用于整数。您可以使用equalsequalsIgnoreCase 的方法来比较字符串是否为大写。

if (Answer1 == "animal" && Answer2 == "yes") {
        JOptionPane.showMessageDialog(null, "Your item is: A Moose");
    }

所以,在你的情况下,你可以使用equals

if (Answer1.equals("animal") && Answer2.equals("yes")) {
        JOptionPane.showMessageDialog(null, "Your item is: A Moose");
    }

【讨论】:

    【解决方案2】:

    您不能在 Java 中为Strings 使用== 条件运算符,因为它们是Objects。

    当您对对象使用== 时,它会比较其地址的值而不是实际值。

    改为使用

    Answer1.equals("animal") && Answer2.equals("yes")
    

    在你的情况下。

    【讨论】:

    • 谢谢朋友
    猜你喜欢
    • 2022-01-23
    • 2023-03-10
    • 1970-01-01
    • 2010-12-14
    • 1970-01-01
    • 2020-02-23
    • 2014-12-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多