0

So I tracked down the bugger, but I am no closer to understanding what is wrong. Here is what the compiler says:

Exception in thread "main" java.lang.NullPointerException at BasicFile.Search(BasicFile.java:215) at TestFile.main(TestFile.java:42)

Line 215 is the one that starts with while, first one.

String Search(String key) throws IOException {

    int lines = 0;
    String line = "";
    String foundAt = "";
    BufferedReader BF = new BufferedReader(new FileReader(f));

    try {
        while ((line = BF.readLine().toLowerCase()) != null) {
            lines++;
            //create tokenizer words with what is in line
            StringTokenizer words = new StringTokenizer(line);
            while(words.hasMoreTokens()) { //while words has tokens left
                //go to next token and compare to key
                if (words.nextToken().equals(key.toLowerCase())) 
                    foundAt = foundAt + "\n" + lines + ":" + line;
                //do nothing continue loop                     
            }
        }
        BF.close();
    } catch(FileNotFoundException e) {
    }
    return foundAt;
}
4
  • You put != to check if the value returned is not null. But you're using the value returned by invoking a method on it... Commented Mar 2, 2014 at 23:04
  • Why do you have != null? What could be null? The answer is the value returned by BF.readLine(). If that can be null, why are you invoking a method on it? Commented Mar 2, 2014 at 23:06
  • I was trying to be all tricky and doing it all on one line... I should have been more careful. My shame to live with. Commented Mar 2, 2014 at 23:15
  • Till the end of days. Commented Mar 2, 2014 at 23:16

4 Answers 4

2

When your buffer reader runs out of lines it returns null. You are trying to call toLowerCase method on null which ends up throwing the null pointer exception.

Refactor your code in a way that it doesn't require you to execute toLowerCase before ensuring the line is non-null.

For example:

String next;

while ((next = BF.readLine()) != null) {
   String line = next.toLowerCase();
   // ...
}
Sign up to request clarification or add additional context in comments.

1 Comment

ah! I see, now the tricky part will be finding a way to do that.
0
while ((line = BF.readLine().toLowerCase()) != null)

What happens if BF.readline() returns null?

3 Comments

null pointer exception... I just learned that 10 seconds ago.
@user3236502: Indeed, you are trying to call a method on null. Test for null before doing that.
@user3236502: That is why i phrased the answer as a question. Good luck.
0

remove .toLowerCase() from the test

2 Comments

But I must make it lowercase otherwise it may not return a value like Cat will be not found if I am looking for cat.
jsalonen replied to you. I cannot explain it better than him.
0

Please, stop it, your code is giving me cancer! There are a number of stylistic errors in the code that you need to fix.

  • First off in java, method names always begin with a lowercase letter. You are programming in Java, not C#, so you need to use the Java naming conventions. That means your method should be called search, not Search.
  • The same goes for variable names. What is BF supposed to mean, anyway? Replace it with in, please.
  • Next up, unless this method is in an object that itself represents that particular file, the global variable f should be passed as a parameter instead.
  • BufferedReader is AutoCloseable, so you should use a try-with-resources to deal with closing it.
  • You need to add a javadoc comment to it, documenting its parameters with @param, its return with @return, and exactly why it might need to throw an IOException with @exception.

Here is a mostly-fixed version of your code:

/**
 * Needs Javadoc
 */
String search(String key, File f) throws IOException {

    int lines = 0
    String line = "";
    String foundAt = "";

    try(BufferedReader in = new BufferedReader(new FileReader(f)) {

        while ((line = in.readLine().toLowerCase()) != null) { //the line in question

            lines++;
            StringTokenizer words = new StringTokenizer(line);

            while(words.hasMoreTokens()) 
                if (words.nextToken().equals(key.toLowerCase()))
                    foundAt = foundAt + "\n" + lines + ":" + line;                     
        }

    } catch(FileNotFoundException e){}

    return foundAt;
}

Now, the problem here is that in.readline() returns a null sometimes. Calling a method on a null is always a NullPointerException. Therefore you get a NullPointerException when you attempt to call that null's missing toLowerCase() method.

You need to convert it toLowerCase after you ensure it is non-null.

3 Comments

I just do things the way the professor asks, he is the one that set up the global variable. BF and Search.
@user3236502 don't let yourself be cheated out of proper education! You should demand that to be taught real java.
@user3236502 If I were teaching a programming class, I would take off major points from any code that didn't use proper style, even if the bad style was from bad template code given to students.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.