0

I'm reading a CSV file using Java. Inside the file, each row is in this format:

operation, start, end.

I need to do a different operation for different input. But something weird happened when I'm trying to compare two string.

I used equals to compare two strings. And one of the operation is "add", but the first element I fetched from the document always give me the wrong answer. I know that's an "add" and I printed it out it looks like an "add", but when I'm using operation.equals("add"), it's false. For all rest of Strings it's correct except the first one. Is there anything special about the first row in CSV file?

Here is my code:

while ((line = br.readLine()) != null) {
    String[] data = line.split(",");
    String operation = data[0];
    int start = Integer.parseInt(data[1]);
    int end = Integer.parseInt(data[2]);
    System.out.println(operation + " " + start + " " + end);
    System.out.println(operation.equals("add"));

For example, it printed out add 1 3 false add 4 6 true And I really don't know why. These two add looks exactly the same.

And here is what my csv file look like: enter image description here

Guanda Li
  • 11
  • 2

3 Answers3

2

There are (at least) 4 reasons why two string that "look" like they are the same when you display / print them could turn out to be non-equal:

  1. If you compare Strings using == rather than equals(Object), then you will often get the wrong answer. (This is not the problem here ... since you are using the equals method. However, this is a common problem.)

  2. Unexpected leading or trailing whitespace characters on one string. These can be removed using trim().

  3. Other leading, trailing or embedded control characters or Unicode "funky" characters. For example stray Unicode BOM (byte order mark) characters.

  4. Homoglyphs. There are a number of examples where two or more distinct Unicode code points are rendered on the screen using the same or virtually the same glyphs.

Cases 3 and 4 can only be reliably detected by using traceprints or a debugger to examine the lengths and the char values in the two strings.

(Screen shots of the CSV file won't help us to diagnose this! A cut-and-paste of the CSV file might help.)

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
0

You should remove the double quotes from the first element and then check with equals method.

Try this:

String operation = operation.substring(1, to.length() - 1);
operation.equals("add")

Hope it works for you.

amar19
  • 373
  • 1
  • 3
  • 16
0

It looks like your line in image looks fine. I suppose in this case, that you could set wrong document encoding. E.g. when UTF, and you do not put it, then is has special header at the beginning. It could be a reason, why you read first word incorrectly.

Oleg Cherednik
  • 17,377
  • 4
  • 21
  • 35