0

I have to write a java program that compare two tables and print the the ones that are not same. 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
yacine benzmane
  • 3,888
  • 4
  • 22
  • 32

1 Answers1

0

As Karthikeyan Vaithilingam pointed out, you have used 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.

Here is a great article on String comparison: http://www.thejavageek.com/2013/07/27/string-comparison-with-equals-and-assignment-operator/

mgthomas99
  • 5,402
  • 3
  • 19
  • 21