简体   繁体   English

与Java中的文本文件比较

[英]Comparing to text files in java

I have to write a java program that compare two tables and print the the ones that are not same. 我必须编写一个Java程序来比较两个表并打印不相同的表。 This my try, but for some reason the program do the complete opposite. 这是我的尝试,但是由于某种原因,该程序执行了完全相反的操作。

 public class reading_file {
    public static void main(String [] args) throws IOException {
        File is1 =new File("T1.txt");
        File is2 =new File("T2.txt");
        Scanner sc1 = new Scanner(is1);
        Scanner sc2 = new Scanner(is2);
        while (sc1.hasNext() && sc2.hasNext()) {
            String str1 = sc1.next();
            String str2 = sc2.next();
            if (str1 != str2)
                System.out.println(str1 + "  " + str2);
        }
        while (sc1.hasNext())
            System.out.println(sc1.next() + " != EOF");
        while (sc2.hasNext())
            System.out.println("EOF != " + sc2.next());
        sc1.close();
        sc2.close();
    }
}

This is the tables: 这是表格:

ID Name   
1   A
26  Z
3   C
ID Name
1   A
2   B
3   C

And this is my output 这是我的输出

1  1
A  A
26  2
Z  B
3  3
C  C

As Karthikeyan Vaithilingam pointed out, you have used if (str1 != str2) . 正如Karthikeyan Vaithilingam指出的那样,您使用了if (str1 != str2) This is incorrect. 这是不正确的。 Using the != conditional operator compares the two String objects rather than their actual value, in which case your code will continue to run. 使用!=条件运算符将比较两个String对象而不是它们的实际值,在这种情况下,您的代码将继续运行。

Here is a great article on String comparison: http://www.thejavageek.com/2013/07/27/string-comparison-with-equals-and-assignment-operator/ 这是一篇关于String比较的好文章: http : //www.thejavageek.com/2013/07/27/string-comparison-with-equals-and-assignment-operator/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM