尝试使用hashmap来计算数组中单词的频率

时间:2020-11-27 21:36:40

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?

我一直得到“histogram.put(word,f + 1);”的NullPointerException。部分。为什么是这样?

1 个解决方案

#1


10  

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

发生这种情况是因为如果在地图中找不到该值,则f将为null。在for循环中尝试这个。

Integer f = histogram.get(word);
if (f == null) {
    histogram.put(word, 1);
} else {
    histogram.put(word, f+1);
}

#1


10  

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

发生这种情况是因为如果在地图中找不到该值,则f将为null。在for循环中尝试这个。

Integer f = histogram.get(word);
if (f == null) {
    histogram.put(word, 1);
} else {
    histogram.put(word, f+1);
}