0

我正在编写一个简单的程序,在其中我需要获取用户输入的是/否(我正在使用扫描仪,UI,为此),如下所示:

    System.out.println("Do you know the insulation capacity? (y/n) ");
    String IC = UI.nextLine();

这工作得很好,但我在下一部分遇到了麻烦,我在 if 语句中检查字符串:

    if(IC == "y" || IC == "Y" || IC == "yes" || IC == "Yes"){ //four options of saying "yes"
        System.out.print("What is the insulation capacity? ");
        m = UI.nextDouble();
    }else if(IC == "n" || IC == "N" || IC == "no" || IC == "No"){ //four options of saying "no"
        findM();
    }else{
        System.out.println("Answer was not clear. Use y, n, yes, or no.");
        checkM();
    }

当我运行程序时,总是执行 else,即使 IC 是 Y、y、Yes... 等等。

为什么会这样,我该如何让它发挥作用?

谢谢,

-正义

4

2 回答 2

1

你应该比较Stringsequals不是==。否则,您将比较参考,而不是它们的价值,这正是您想要的。

此外,在这种情况下,equalsIgnoreCase可能对您有所帮助。您只需要 2 次比较而不是 4 次。

例子:

if(IC.equalsIgnoreCase("y") || IC.equalsIgnoreCase("yes"))
于 2014-03-08T23:16:10.547 回答
0

您不能使用 == 运算符比较 Java 中的字符串。对每个 Object-Type 使用 equals。在您的情况下,最好的解决方案是使用像 ic.equalsIgnoreCase("y") || 这样的条件 ic.equalsIgnoreCase("是")

于 2014-03-08T23:18:15.863 回答