【问题标题】:Trying to use hashmap to count frequency of words in array尝试使用 hashmap 来计算数组中单词的频率
【发布时间】:2014-05-20 13:37:26
【问题描述】:

这是我的代码:

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);
}

我不断收到“ histogram.put(word,f+1);”的 NullPointerException部分。这是为什么呢?

【问题讨论】:

  • 如果fnull 会发生什么?
  • 另外,看看 Guava Multiset。这是一个类似的数据结构,专门用于计算项目的出现次数。

标签: java arrays nullpointerexception hashmap


【解决方案1】:

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

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

【讨论】:

  • 拍摄,我很生气我没有把它捡起来。现在可以了,非常感谢!
猜你喜欢
  • 2015-01-07
  • 1970-01-01
  • 1970-01-01
  • 2019-01-27
  • 2023-03-22
  • 2014-01-07
  • 2011-07-21
相关资源
最近更新 更多