I just started learning java and I'm trying to count the number of times a word appeared in a string which I passed it. I'm using the HashMap class, the words I pass are the key and their count is the value. I can't figure out why I keep getting a NPE exception in the counter, the for loop looks right to me, did I use the split function incorrectly?
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"));
}
}