这是我的代码:

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。部分。为什么是这样?

最佳答案

发生这种情况是因为如果在 map 中找不到该值,那么f将为null。在for循环内尝试此操作。

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

10-06 02:20