0

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.

Tagyoureit
  • 359
  • 1
  • 5
  • 18

1 Answers1

2

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("&")) {
Pshemo
  • 122,468
  • 25
  • 185
  • 269
s.fuhrm
  • 438
  • 4
  • 9