if语句中的多个字符串条件

时间:2014-03-08 23:07:23

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

我正在编写一个简单的程序,在其中我需要获取用户输入的是/否(我正在使用Scanner,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();
    }

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

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

谢谢,

-Justice

2 个答案:

答案 0 :(得分:1)

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

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

示例:

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

答案 1 :(得分:0)

您无法使用==运算符比较Java中的字符串。使用equals代替每个Object-Type。在您的情况下,最佳解决方案是使用类似ic.equalsIgnoreCase(“y”)||的条件ic.equalsIgnoreCase( “是”)

相关问题