java - 当它们打印相同的东西时,为什么两个字符串不相等?
问题描述
这可能是一个愚蠢的问题,但老实说我不知道我做错了什么。我创建了一个类来读取文件并打印其中的每个单词。首先,我创建了一个名为“lines”的类的实例。我运行我的程序来查看lines.toString() 打印的内容,然后复制/粘贴结果。我将结果存储在一个名为“result”的字符串变量中,然后我比较了“result”和“lines”。
事实证明,lines.equals(result) 是错误的。这是为什么呢?我只复制并粘贴结果,然后将其与原始结果进行比较。他们从字面上打印相同的东西,所以空白或类似的东西应该没有区别。我知道它有点长,但是如果您想看一下,我的代码在下面。我感谢任何愿意帮助我的人。谢谢!
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
解决方案
推荐阅读
- android - 如何查看 Firebase 事件参数值?
- node.js - 尝试在 mailchimp 中添加联系人时出现错误 400
- r - 如何在闪亮的范围内渲染网格
- web-applications - 使用关键字搜索单个 youtube 视频
- ruby-on-rails - 如何在 Rails 中验证 API 响应状态
- c# - 铸造工作,但不能转换有什么区别,为什么
- laravel - 在 Laravel Eloquent Query 中使用 unaccent PostgreSQL 函数
- sql-server - 将 XML 键值对转换为字符串
- javascript - 在执行脚本之前等待 Jinja 完全完成页面渲染
- assembly - 判断原始源文件是否包含函数调用?