Java 两个字符串相等,但不适用于if语句

Java 两个字符串相等,但不适用于if语句,java,string,if-statement,string-comparison,Java,String,If Statement,String Comparison,比较两个字符串,当我调试时,比较是“Mario”到“Mario”,因此if语句应该是true,但它是false,因为if语句中没有任何内容被读取。为什么会这样?我曾尝试将此.getname分配给一个tempString并对其进行比较,但当它们是相同的字符串时,语句结果仍然为false。请帮助使用 System.out.println(characters.get(selected).getName()); // The name printed is "Mario" But th

比较两个字符串,当我调试时,比较是“Mario”到“Mario”,因此if语句应该是true,但它是false,因为if语句中没有任何内容被读取。为什么会这样?我曾尝试将此.getname分配给一个tempString并对其进行比较,但当它们是相同的字符串时,语句结果仍然为false。请帮助使用

    System.out.println(characters.get(selected).getName());
    // The name printed is "Mario" But the if statement will not
   // work as though the two strings are diffrent but they are the same.
    if(characters.get(selected).getName() == "Mario"){
        playSound("sounds/clickmario.wav");
    }
对于java,它应该可以在javascript中工作

if (stra === strb)
那么它也应该起作用

使用

    System.out.println(characters.get(selected).getName());
    // The name printed is "Mario" But the if statement will not
   // work as though the two strings are diffrent but they are the same.
    if(characters.get(selected).getName() == "Mario"){
        playSound("sounds/clickmario.wav");
    }
对于java,它应该可以在javascript中工作

if (stra === strb)
那么它也应该可以工作了

您必须在java中使用.equals()进行字符串比较

if (stra.equals(strb))
在java中,必须使用.equals()进行字符串比较

if (stra.equals(strb))
。 和 有关字符串的基础知识,请参阅。

。 和
有关字符串的基础知识,请参阅。

==仅适用于简单的primative。您需要使用.equals将字符串对象相互比较。这是正确的。==只适用于简单的灵长类动物。您需要使用.equals将字符串对象相互比较。这是正确的。