0

I'm having a problem with my code I don't know why isn't making the comparison but prints it well. These is my code...

  public void read() throws IOException {
        String entered = one.next(); // Read from the console
        try (BufferedReader reader = new BufferedReader(new FileReader("file.csv"))) {
            while (true) {
                String line = reader.readLine(); // Read file line
                if (line == null) {
                    break;
                } //Break if there is no more lines
                String[] lineTwo = line.split(","); // Split into Array the line to compare it
                if (lineTwo[1].replaceAll(" ", "") == entered.replaceAll(" ", "")) {
                    // compare record 1 with the entered value replace all is not needed I was testing if it have some spaces
                    System.out.println("entered");
                }
                System.out.println(lineTwo[0]);
            }
        }
    }

It print all the information of the file but when I'm going to to compare it the condition never gets printed. First read from the console and then read the file line .. line and compare if the record [1] = entered from the console. For some reason print all but it doesn't enter that if statement.

chengpohi
  • 14,064
  • 1
  • 24
  • 42

1 Answers1

0

Your code:

lineTwo[1].replaceAll(" ", "") == entered.replaceAll(" ", "")

Should be:

lineTwo[1].replaceAll(" ", "").equals(entered.replaceAll(" ", ""))

In Java, You need to know when want to compare String, you need to use the equals method. because == will compare the reference of String object. so if you compare two String objects, the reference it's not same.

chengpohi
  • 14,064
  • 1
  • 24
  • 42