0

I have a file with values like:

a,9,1

b,2,4

c,2,4

till *,2,0 and this is my code:

    public static final String letterFileLoc = "filelocation";
    public static Map<Character, Integer> letterValueMap;
    public static Map<Character, Integer> letterCountMap;
    public static void constructLetterMaps() throws FileNotFoundException{
    File pointvals = new File(letterFileLoc);
    Scanner pts = new Scanner(pointvals);
    while (pts.hasNext()){
        String [] parts = pts.next().split(",");
        char alpha = (parts[0]).charAt(0);
        int counts = Integer.parseInt(parts[1]);
        int values = Integer.parseInt(parts[2]);
        letterValueMap.put(alpha, values);
        letterCountMap.put(alpha, counts);
      }

and I keep getting a null pointer expception when I'm putting the values. I don't understand why. Could someone please explain?

centrinok
  • 300
  • 2
  • 11

2 Answers2

2

You need to initialize letterValueMap and letterCountMap like this:

letterValueMap = new HashMap<Character, Integer>();
letterCountMap = new HashMap<Character, Integer>();

Put that code anywhere in your class where it will be run before the two Maps are used.

You can also initialize them when they declared, like this:

public static Map<Character, Integer> letterValueMap = new HashMap<Character, Integer>();
public static Map<Character, Integer> letterCountMap = new HashMap<Character, Integer>();
The Guy with The Hat
  • 10,836
  • 8
  • 57
  • 75
1

You have

 public static Map<Character, Integer> letterValueMap;
 public static Map<Character, Integer> letterCountMap;

... but you have not initialised them. You need to call the constructors somewhere; e.g.:

 static{
   letterValueMap = new HashMap<Character, Integer>();
   letterCountMap = new HashMap<Character, Integer>();
 }
badroit
  • 1,316
  • 15
  • 28