Count number of lines that starts with & character in CSV file

Tagyoureit :

I am trying to make a function that will count how many lines starts with & in given file. So far i came up with following function

  public int CountNumberOfTexts(String filename)  {

        try{

            File file = new File(filename);

            if(file.exists()){

                FileReader fr = new FileReader(file);
                LineNumberReader lnr = new LineNumberReader(fr);

                int linenumber = 0;

                while (lnr.readLine() != null){
                    if (lnr.readLine().substring(0,1) == "&") {
                        linenumber++;
                    }
                }

                Log.d("Count", "NUMBER OF LINES: " + linenumber);

                lnr.close();

                return linenumber;

            }else{
                System.out.println("File does not exists: " + filename);
            }

        }catch(IOException e){
            e.printStackTrace();
        }

        return 0;
    }

Current Function error is: Not recognizing lines starting with & character.

s.fuhrm :

You are facing two problems:

  1. You are reading in two lines, but only evaluating every second:

    while (lnr.readLine() != null){  <- first consumption
    if (lnr.readLine().substring(0,1) == "&") { <- second
    
  2. You are comparing strings with == operator instead of equals method. Or in your case you can even use startsWith method which is created precisely for scenarios like yours.

This will do the trick:

String line;
while ((line = lnr.readLine()) != null){
    if (line.startsWith("&")) {

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=19130&siteId=1