This question already has answers here:
How do I compare strings in Java?

(23个答案)


6年前关闭。





我正在编写一个简单的程序,在其中我需要获取用户输入是/否的信息(为此,我正在使用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,Yes等,也始终执行else。

为什么会这样,如何使它正常工作?

谢谢,

-正义

最佳答案

您应该将Stringsequals而不是==进行比较。否则,您将要比较引用,而不是它们的值。

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

例:

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

10-06 03:34