1

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

}
ikos23
  • 4,879
  • 10
  • 41
  • 60
CISSflow
  • 89
  • 5
  • 1
    The map is not being initialized until `map = new HashMap();` which is in the zero paramater constrcutor, which is **not** being called – Scary Wombat Oct 01 '18 at 07:05
  • 1
    `public WordCount(String words)` constructor isn't calling the `public WordCount()` constructor, therefore `map` is `null` – MadProgrammer Oct 01 '18 at 07:06
  • 1
    Add `this()` at the first line of `public WordCount(String words) {` constructor. – Kaustubh Khare Oct 01 '18 at 07:07
  • 2
    An option would be adding an instantiation to your class attribute: `private HashMap map = new HashMap();` – deHaar Oct 01 '18 at 07:07
  • You have put the hashmap initialisation in the wrong constructor. – subzero Oct 01 '18 at 07:08
  • There is no real need to have two constructors here: only the `()` one is needed to create the instance in a valid state (which is the purpose of a constructor); there other is really just a convenience to say "create an instance, and add data to it". A better approach would be to remove the second, and add a static factory method which literally does create the instance and invoke add repeatedly, then return the instance. (Additionally, `map.merge` is an easier way to implement the `addWord` method). – Andy Turner Oct 01 '18 at 08:05

0 Answers0