1

I am trying to parse a CSV file that has the format: name, gender, popularity.I want to count all the females present inside the file but I unable to do so. Here's a sample data from the file : Mary, F, 51479. Here's my code :

import java.io.*;

public class CSVFile {
    public static void main(String [] args)throws IOException{
        String file_name = "xyz.csv";

        BufferedReader f = new BufferedReader(new FileReader(file_name));

        String line ;

        int female_count = 0;

        while ((line = f.readLine()) != null){

            String [] values = line.split(",");

            if (values[1] == "F"){
                female_count += 1;
            }
        }
        System.out.println(female_count);

    }
}

Can someone please explain it to me that why is my "if" statement not running? Thank You !!

Jimmy15
  • 19
  • 4
  • 1
    You need to use ```equals``` method for string operation. ```==``` compares the address of both object and hence will always be false. – Umeshwaran Feb 02 '21 at 21:40
  • 1
    ```if (values[1].equals("F"))``` should be the valid code . – Umeshwaran Feb 02 '21 at 21:41
  • I really hate it when beginners complain that if-statements aren't working. So far, this has always been a case of String comparison not using String#equals(). Just ask yourself one question: are you more likely to make a mistake in your code, or for you to find a compiler bug? – NomadMaker Feb 02 '21 at 21:49

1 Answers1

3

The following String Mary, F, 51479, when split by ,, will return an array with items Mary, F, and 51479. Notice that the leading spaces will make a .equals() comparison return false in your code.

In short, .split() will include a leading space in every item after the first in your example, so use .trim() to remove leading and tailing spaces. You are also not comparing Strings properly - use .equals().

The following should work:

import java.io.*;

public class CSVFile {
    public static void main(String [] args)throws IOException{
        String file_name = "xyz.csv";

        BufferedReader f = new BufferedReader(new FileReader(file_name));

        String line ;

        int female_count = 0;

        while ((line = f.readLine()) != null){

            String [] values = line.split(",");

            if (values[1].trim().equals("F")){
                female_count += 1;
            }
        }
        System.out.println(female_count);

    }
}
Spectric
  • 30,714
  • 6
  • 20
  • 43