-1

I try to find how many fender words in my txt file but I get nullPointerException. I m waiting for your helps. Thank you :)

public class ScanTxt {

private static BufferedReader buffer;
static int count=0;


public static void main(String...args) throws IOException{
readFile();
}
public static int readFile() throws IOException {
    buffer = new BufferedReader(new FileReader("C:/Users/ASUS/Desktop/myfile.txt"));

        StringBuilder strbuild = new StringBuilder();
        String line = bufferr.readLine();

        while (line!=null) {
            strbuild.append(line);
            strbuild.append("\n");
            line = buffer.readLine();
            if(line.equalsIgnoreCase("fender")){
                count++;
            }
        }
        return count;


}
Victory
  • 5,811
  • 2
  • 26
  • 45
ozanonurtek
  • 306
  • 5
  • 18

1 Answers1

2

You are reading your line to soon inside the while so it can be null in line.equalsIgnoreCase (as your while loop stops)

Try

   while (line!=null) {
        strbuild.append(line);
        strbuild.append("\n");
        if(line.equalsIgnoreCase("fender")){
            count++;
        }
        line = buffer.readLine();
    }
Victory
  • 5,811
  • 2
  • 26
  • 45
  • I think the most appropriate way would be to put `.readLine()` only in while condition. `while((line=buffer.readLine())!=null)`. – itwasntme Sep 02 '15 at 23:17