首页 > 解决方案 > 当它们打印相同的东西时,为什么两个字符串不相等?

问题描述

这可能是一个愚蠢的问题,但老实说我不知道​​我做错了什么。我创建了一个类来读取文件并打印其中的每个单词。首先,我创建了一个名为“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

标签: java

解决方案


if (lines.equals(result)) {

lines是一个Documentresult而是一个String

所以他们不可能相等。比较DocumentandString就像比较苹果和橘子

Document正如你忽略的那样,我不知道什么是 class 。

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

将此字符串与指定对象进行比较。结果是true当且仅当参数不为 null 并且是String表示与此对象相同的字符序列的对象。


推荐阅读