If Else: 字符串相等 (Java)

If Else: String Equality (Java)

实验说明:比较两个字符串,看看这两个字符串是否都包含相同的字母 同样的顺序。

这是我目前所拥有的:

import static java.lang.System.*;

public class StringEquality
{
   private String wordOne, wordTwo;

   public StringEquality()
   {
   }

   public StringEquality(String one, String two)
   {
      setWords (wordOne, wordTwo);
   }

   public void setWords(String one, String two)
   {
      wordOne = one;
      wordTwo = two;
   }

   public boolean checkEquality()
   {
      if (wordOne == wordTwo)
      return true;
      else
      return false;
   }

  public String toString()
  {
    String output = "";
    if (checkEquality())
    output += wordOne + " does not have the same letters as " + wordTwo;
    else
    output += wordOne + " does have the same letters as " + wordTwo;
    return output;
  }
}

我的跑步者看起来像这样:

import static java.lang.System.*;
public class StringEqualityRunner
{
public static void main(String args[])
{
    StringEquality test = new StringEquality();

    test.setWords(hello, goodbye);
    out.println(test);


}
}

除跑步者外,一切都在编译。它一直在说你好和再见不是变量。我怎样才能解决这个问题,使程序不会将 hello 和 goodbye 作为变量读取,而是作为字符串读取?

您需要引用字符串,否则它们将被视为变量。

"hello"
"goodbye"

这样效果会更好。

test.setWords("hello", "goodbye");

用双引号将它们括起来。

您的代码有问题 checkEquality(),当您使用 == 使用 .equals() 检查字符串

时,您正在比较字符串在内存中的位置
public boolean checkEquality()
{ 
  if (wordOne == wordTwo) //use wordOne.equals(wordTwo) here
     return true;
  else
     return false;
}