gpt4 book ai didi

java - 当两个字符串打印相同的内容时,为什么它们不相等?

转载 作者:行者123 更新时间:2023-12-02 01:01:53 26 4
gpt4 key购买 nike

这可能是一个愚蠢的问题,但老实说我不知道​​我做错了什么。我创建了一个类来读取文件并打印其中的每个单词。首先,我创建了一个名为“lines”的类的实例。我运行程序来查看lines.toString() 打印的内容,然后复制/粘贴结果。我将结果存储在名为“结果”的字符串变量中,然后比较“结果”和“行”。

事实证明,lines.equals(result) 是 false.. 这是为什么?我只是复制并粘贴结果,然后将其与原始结果进行比较。它们实际上打印相同的内容,因此空白或类似内容应该没有差异。我知道它有点长,但如果您想看一下,我的代码在下面。我很感激任何愿意帮助我的人。谢谢!

public Document(String fileName) throws FileNotFoundException {
File file;
Scanner docScanner;

String curLine;
numLines = 0;
numWords = 0;

file = new File(fileName);
docScanner = new Scanner(file);

while (docScanner.hasNext()) {
docScanner.nextLine();
numLines++;
}

docScanner = new Scanner(file);
words = new String[numLines][];

for (int i = 0; i < words.length; i++) {
curLine = docScanner.nextLine();
words[i] = curLine.trim().split("\\s");

if (words[i][0].equals("")) {
words[i] = new String[0];
} else {
for (int j = 0; j < words[i].length; j++) {
numWords++;
}
}
}
}

public String getLine(int lineNum) throws NoSuchLineException {
String result = "";
for (int i = 0; i < words[lineNum].length; i++) {
result = result + words[lineNum][i] + " ";
}
return result;
}

public String toString() {
String result = "";
for (int i = 0; i < words.length; i++) {
result = result + getLine(i) + "\n";
}
return result;
}

public static void main(String[] args) throws FileNotFoundException {
Document lines = new Document("file.txt");

String result = "Mary had \r\n" +
"a little lamb \r\n" +
"Its fleece was \r\n" +
"white \r\n" +
"as snow ";

if (lines.toString().equals(result)) {
System.out.println("They are equal");
} else {
System.out.println("Not equal");
}
}

file.txt is below:
Mary had
a little lamb
Its fleece was
white
as snow

最佳答案

if (lines.equals(result)) {

lines 是一个 Document,而 result 是一个 String .

所以它们不能相等。比较 DocumentString 就像比较 apples and oranges .

我不知道Document是什么类,因为你没有提到。

关于String,它的equals方法需要同一类的对象。引用文档:

Compares this string to the specified object. The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object.

关于java - 当两个字符串打印相同的内容时,为什么它们不相等?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60553524/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com