Assignment: Create a program to practice reading in from a file, search for a particular word when the user inputs a word to search for and a file via command line args. Print out the entire line each time it is found.
Progress:
It compiles, and runs.... kinda.
Problem: I get a null pointer exception on line the line where I end the check for the word im searching for.

public class FindString{
    public static void main(String args[]) throws FileNotFoundException, 
                                                  IOException{
        if(args.length != 2){
            System.err.println("Usage: java FindString search-string " 
                               + "file-name");
        }
        String searchString = args[0]; //word to search for
        String fileName = args[1]; // filename
        FileReader fred = null;
        try{
            fred = new FileReader(fileName);
        }
        catch(FileNotFoundException fnf){
            System.err.println("FileNotFoundException occurred: " +
                               fnf.getMessage());
        }
        try{
            BufferedReader bread = new BufferedReader(fred); 
        int index;
        String currentLine = "";
        while(currentLine != null){ //read line by line while searching
            currentLine = bread.readLine();
            index = currentLine.indexOf(searchString); //NULLPOINTEREXCEPTION
            if(index > 0){ // positive index if found
                System.out.println(currentLine);
            }
        }
            bread.close();
        }
       
        catch(IOException ioe){
            System.err.println("IOException occurred: " + ioe.getMessage());
        }
            

            }
}

Why do i get the null pointer exception and how can I get rid of it???

You're checking for null before you've read the next line, a quick change to:


while( (currentLine = bread.readLine() ) != null){ //read line by line while

should fix it

Hello lrolsto1.
You need to consider the values your variables are getting in every iteration through the while loop. The problem is, that a variable is taking null value in some iteration of the while loop, thus resulting in a NullPointerException being thrown.
So you need to check the values your variables are taking.

Edited 6 Years Ago by BhagatS: n/a

This article has been dead for over six months. Start a new discussion instead.