5

This is my code:

public static void main(String args[]) throws Exception
{
    BufferedReader infile = new BufferedReader(new FileReader(args[0]));
    HashMap<String,Integer> histogram = new HashMap<String,Integer>();
    while ( infile.ready() )
    {   
        String SPACE = " ";
        String [] words = infile.readLine().split(SPACE);

        for (String word : words)
        {
            Integer f = histogram.get(word);
            histogram.put(word,f+1);
        }   
    }
    infile.close();
    printHistogram( histogram );
}
private static void printHistogram( HashMap<String,Integer> hm )
{
    System.out.println(hm);
}

I keep getting a NullPointerException for the " histogram.put(word,f+1);" part. why is this?

2
  • What happens if f is null? Commented Apr 8, 2014 at 3:55
  • Also, look at Guava Multiset. It's a similar data structure specifically built for counting the occurrences of items. Commented Apr 8, 2014 at 5:21

1 Answer 1

11

This happens because f will be null if the value is not found in the map. Try this, inside the for loop.

Integer f = histogram.get(word);
if (f == null) {
    histogram.put(word, 1);
} else {
    histogram.put(word, f+1);
}
Sign up to request clarification or add additional context in comments.

1 Comment

shoot, I'm mad that I didn't pick that up. it works now, thank you very much!

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.