简体   繁体   中英

Hashtable NullPointerException

I have an assignment to design a simple spam filter using a hash table to store a set of "bad words." We discussed in class what a hash table is and how it's used (ie. how elements are inserted, linear probing, quadratic probing, chained probing, etc.), but we never really discussed how to use the Java API Hashtable, which is required for this assignment. anyway, I've tried my best to implement it, however, I'm getting an exception that I cannot seem to trace with my debugger.

I've given up with inserting code here, I always have to spend time formatting it properly and it still doesn't look good. So I'm putting it on Pastebin instead. It should make your lives easier too since it does syntax highlighting and line counting as well.

SpamFilter class
SpamFilterDriver class

I get NullPointerExceptions at the following lines in the SpamFilterDriver class:
line 78
line 96
line 115

Any help would be appreciated. I'm sure it's probably something silly, but I'm just not seeing it at the moment.



Also, please note that the code is not finished yet in the least. The fact that the SpamFilter implements Serializeable will be used later on. Also, there are some empty methods, again, they will be implemented later, I just need to solve this problem first.

you have to initialize your SpamFilter filter; in your SpamFilter Class. before calling any of its methods.

on line 78, you are calling a method isBadWord() .

try initializing filter like below before calling any of its method. if you dont initialize your filter the default value is null and boom when you call a method with null BOOM BOOM NPE is thrown

    private static SpamFilter filter = new SpamFilter();// 

In each one of those lines, observe that you are invoking a method of filter . Java is throwing getting a NullPointerException because filter 's value is null .

Why is its value null ? Because you never assigned it a value; you merely declared it. You can set its value right as you declare it or, since it's a static field, you can use a static constructor to assign it a value.

Your filter is not be initialized hence failing wherever its being used. Its only declared in the top as private static SpamFilter filter; , which makes filter as null.

To fix the problem, initialize the filter either at declaration as

      private static SpamFilter filter = new SpamFilter(); 

or in main() method before while loop as

      filter = new SpamFilter();

Looks like you never initialize the filter property, so you get a NullPointerException whenever you try and use it.

Try replacing line 6 with:

private static SpamFilter filter = new SpamFilter();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM