【问题标题】:Multiple string conditions in an if statement [duplicate]if语句中的多个字符串条件[重复]
【发布时间】:2014-04-12 03:27:22
【问题描述】:

我正在编写一个简单的程序,在其中我需要获取用户输入的是/否(我正在使用扫描仪,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... 等等。

为什么会出现这种情况,我该如何让它发挥作用?

谢谢,

-正义

【问题讨论】:

  • ic.equalsIgnoreCase("y") || ic.equalsIgnoreCase("yes")
  • 永远不要(除非您真正了解自己在做什么)使用== 来比较字符串或浮点数。在大多数语言中都是如此,而不仅仅是 Java。

标签: java if-statement conditional-statements multiple-conditions


【解决方案1】:

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

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

例子:

if(IC.equalsIgnoreCase("y") || IC.equalsIgnoreCase("yes"))

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 非常感谢!这很有效,只是像 Hugo 所说的那样将“==”更改为“=”不起作用(尽管它是正确的),但是 IC.EqualsIgnoreCase("Y") 可以。
    • 我没说要把==改成= :o
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-02
    • 1970-01-01
    • 1970-01-01
    • 2016-12-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多