0

I am quite new to Java so this may be a naive question. I am trying to read a CSV file which each line looks like below:

1,"4CC0D97F9ECC6B1A","MUTSAARD","7",1,"7-8",0,0,"ACT"

I used the below code to read this line:

BufferedReader reader = new BufferedReader(new FileReader(attributesFile));
String agent = null;
while ((agent = reader.readLine()) != null) {
    String[] attributeSpilted = agent.split(",");
    
    String agentGender = attributeSpilted[4] == "1" ? "m" :"f";

    System.out.println(agentGender);

    // using a break here for test purposes, delete when finish in the future
    break;
}

So ideally, as the 5th element in this line is 1, the agentGender should be a String variable which == "m", however, after running this code it returns an "f".

I guess the problem is because there is no "" in the original data for the fifth element, but I don't know how should I fix this problem? In other words, what's the type of data when reading CSV elements without a quotation mark?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Jingjun
  • 177
  • 7
  • 1
    "_I guess the problem is because there is no "" in the original data for the fifth element_" - nope, that's not the issue. The issue is that you are incorrectly comparing strings with `==`. Use `equals()` isntead. – maloomeister Oct 26 '21 at 09:14
  • @MaartenBodewes, sorry it was a typo, MB :) – Jingjun Oct 26 '21 at 09:16
  • The 5th element woud be 1, right? How should that be converted to `"m"`? In general, CSV data is _text_ which you need to _parse_ according to whatever rules you need. Double quotes in CSV are used to escape values that could contain the separator as well, so `"MUTSAARD"` and `MUTSAARD` would be the same from a CSV point of view. – Thomas Oct 26 '21 at 09:16
  • 3
    Please use a CSV parser instead of trying to do this yourself. In any case, everything in a CSV file is a string. Interpretation as specific datatypes is the responsibility of the application. – Mark Rotteveel Oct 26 '21 at 09:16
  • @maloomeister, indeed, thanks very much! Issue solved – Jingjun Oct 26 '21 at 09:16
  • Hi everyone, so I find the problem because I used to use R to get the CSV, and by adding a `quote == FALSE` in the original write.table, all quotation marks are deleted so this is more likely a R question. But thanks every :) – Jingjun Oct 26 '21 at 09:30

0 Answers0