我刚刚开始学习Java,我试图计算一个单词在我传递给它的字符串中出现的次数。我正在使用HashMap类,我传递的单词是键,它们的计数是值。我不知道为什么我总是在计数器中出现NPE异常,for循环在我看来正确,我是否正确使用了split函数?
import java.util.HashMap;
public class WordCount {
private HashMap<String,Integer> map;
public WordCount() {
map = new HashMap<String,Integer>();
}
public WordCount(String words) {
String[] list = words.split(",");
for(int i = 0; i < list.length; i++) {
if(!map.containsKey(list[i])) {
map.put(list[i],1);
} else {
map.put(list[i],map.get(list[i])+1);
}
}
}
public void addWord(String toAdd) {
if(!map.containsKey(toAdd)) {
map.put(toAdd,1);
} else {
map.put(toAdd,map.get(toAdd)+1);
}
}
public void startOver() {
if(map.isEmpty()) {
return;
} else {
for(String s: map.keySet()) {
map.remove(s);
}
}
}
public int countWord(String word) {
return map.get(word);
}
}
/ ******************************************* /
public class Main
{
public static void main(String[] args)
{
String s = "hello,bye,how,are,you,ok";
WordCount wordC = new WordCount(s);
System.out.println("Number of Words: " + wordC.countWord("how"));
}
}