0

I'm a Java Beginner. I have a CSV file in the format (City;Gender;Age). e.g how can I count how many males , age < 40 live in a certain city. Any Suggestions?

public void method() throws IOException {
     int count = 0;
     FileReader fr = new FileReader(file);
     BufferedReader br = new BufferedReader(fr);
     String line;
     while((line = br.readLine())!= null){
         br.readLine();
         String [] l = line.split(";");
          if(l[0].equals("CityA")&&l[1].equals("M")&&l[2].equals("<40")) {
              count++;
          }    
      }
}
mypetlion
  • 2,415
  • 5
  • 18
  • 22
K-Mei
  • 13
  • 2
  • What's wrong with your current implementation? How does the behaviour differ from your expectations? Can you show us some sample data and what your program produces vs. what you expect to happen? – mypetlion May 01 '19 at 16:11
  • Possible duplicate of [Can you recommend a Java library for reading (and possibly writing) CSV files?](https://stackoverflow.com/questions/200609/can-you-recommend-a-java-library-for-reading-and-possibly-writing-csv-files) – Benjamin Urquhart May 01 '19 at 16:12

3 Answers3

1

Can be done with streamAPI:

long count = Files.lines(Paths.get(PATH_TO_CSV))
            .map(s -> s.split(";"))
            .filter(arr -> arr[0].equals("CityA"))
            .filter(arr -> arr[1].equals("M"))
            .filter(arr -> Integer.parseInt(arr[2]) < 40)
            .count();

System.out.println(count);
Ruslan
  • 6,090
  • 1
  • 21
  • 36
0

You are trying to do "string".equals("<40") which is checking if the string "string" is equivalent to the string "<40", not if that value is less than 40.

Try converting the string at l[2] to an integer, and then doing the check:

int age = Integer.parseInt(l[2]);
if (l[0].equals("CityA") && l[1].equals("M") && age < 40) {
    count++;
}
Matt
  • 902
  • 7
  • 20
0

If you have line = br.readline() at the beginning of the while, you don't need the second statement br.readline(); inside the while as well. Are you not getting the correct answer? Are you trying to improve code style?

Matt
  • 902
  • 7
  • 20
ladyskynet
  • 297
  • 1
  • 3
  • 10