String If-Else:字符串相等(Java)
实验说明:比较两个字符串,看看这两个字符串中的每个字符串是否包含相同的字母 同样的顺序 到目前为止,我已经做到了:String If-Else:字符串相等(Java),string,if-statement,equality,String,If Statement,Equality,实验说明:比较两个字符串,看看这两个字符串中的每个字符串是否包含相同的字母 同样的顺序 到目前为止,我已经做到了: import static java.lang.System.*; public class StringEquality { private String wordOne, wordTwo; public StringEquality() { } public StringEquality(String one, String two)
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和bye作为变量读取,而是作为字符串读取 您需要引用字符串,否则它们将被视为变量
"hello"
"goodbye"
所以这会更好
test.setWords("hello", "goodbye");
用双引号括起来。代码的问题在于
检查相等()
,当您使用==
使用.equals()
检查字符串时,您正在比较字符串在内存中的位置
public boolean checkEquality()
{
if (wordOne == wordTwo) //use wordOne.equals(wordTwo) here
return true;
else
return false;
}
除了答案中的内容外,您不会将字符串与
=
进行比较。使用equals()
。描述是否建议能够检测到两个字符串包含相同的字符序列?在这种情况下,解决方案将更加复杂。