Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to use hashmap to count frequency of words in array

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?

like image 350
Elisa O Avatar asked Apr 08 '14 03:04

Elisa O


1 Answers

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);
}
like image 142
Dawood ibn Kareem Avatar answered Oct 08 '22 08:10

Dawood ibn Kareem