为什么这会导致运行时错误? (使用 HashMap 查找字符串的字数)

Why is this causing a runtime error? (finding word count of a string using HashMap)

import java.util.HashMap;
import java.util.Iterator;

class L6ex1pt2 {
    String line = "When I was there, it was there"; //works for Strings with all unique words 
                                                    //but not for Strings with repeated words (like this)

    public static void main(String[] args) {
        L6ex1pt2 test = new L6ex1pt2();
        HashMap<String, Integer> hash = new HashMap<String, Integer>();
        hash = test.countWords(test.line);

    }

    public String[] words(String s) {
        String[] words = s.split("\s+");           
        return words;
    }

    public HashMap<String, Integer> countWords(String s) {
        HashMap<String, Integer> wordCount = new HashMap<String, Integer>();
        String[] werds = words(s);
        for (String w: werds) {
            if (wordCount.containsKey(w)) {
                wordCount.put(w, wordCount.get(s)+1);
            } else {
                wordCount.put(w, 1);                
            }
        }
        return wordCount;
    }

}

引发此异常:

线程“main”中的异常java.lang.NullPointerException 在 L6ex1pt2.countWords(L6ex1pt2.java:24) 在 L6ex1pt2.main(L6ex1pt2.java:10)

第 25 行

wordCount.put(w, wordCount.get(s)+1);

应该是

wordCount.put(w, wordCount.get(w)+1);

因为 s 包含整个字符串,而不是您期望的哈希映射键的单词。

在你的第 24 行,你写错了: wordCount.put(w, wordCount.get(s)+1);

应该是:

wordCount.put(w, wordCount.get(w)+1);

将get(s)+1替换为get(w)+1

完整代码:

import java.util.HashMap;
import java.util.Iterator;

public class Main {
    
    String line = "When I was there it was there"; 
    
    public static void main(String[] args) {
        
        Main test = new Main();
        HashMap<String, Integer> hash = new HashMap<String, Integer>();
        hash = test.countWords(test.line);
        System.out.println(hash);
    }

    public HashMap<String, Integer> countWords(String s) {
        HashMap<String, Integer> wordCount = new HashMap<String, Integer>();
        String[] wordsArr = words(s);
        for (String w: wordsArr) {
            if (wordCount.containsKey(w)) {
                wordCount.put(w, wordCount.get(w)+1);
            } else {
                wordCount.put(w, 1);                
            }
        }
        return wordCount;
    }
    
    public String[] words(String s) {
        String[] words = s.split("\s+");           
        return words;
    }
}

输出:

{When=1, there=2, was=2, I=1, it=1}