I am getting the below error:
Exception in thread “main” java.lang.NullPointerException at
HashMap.CountLetters.tallyPrint(CountLetters.java:12) at
HashMap.CountLetters.main(CountLetters.java:21)
The goal is to get store the occurrences of each letter in a HashMap. The key is the letter and the value is the # of occurrences.
package HashMap;
import java.util.HashMap;
public class CountLetters {
public HashMap tallyPrint(String phrase) {
int count = 0;
HashMap<String, Integer> fav = new HashMap<String, Integer>();
for (int i = 0; i<phrase.length(); i++)
{
if (fav.containsKey(phrase.substring(i,i+1)))
fav.put("" + phrase.substring(i,i+1), fav.get(phrase)+1);
else
fav.put("" + phrase.substring(i,i+1),1);
}
return fav;
}
public static void main(String[] args) {
CountLetters x = new CountLetters();
System.out.println(x.tallyPrint("my feet smell and my nose runs"));
}
}
Replace
fav.put("" + phrase.substring(i,i+1), fav.get(phrase)+1);with:
fav.put("" + phrase.substring(i,i+1), fav.get(phrase.substring(i,i+1))+1);Side note1: You should extract that
substringand store it in a temp variable to be more efficient so you don’t keep callingsubstringover and over for the same substring.Side note2: Thanks for posting the whole (with the main method) in your question. It’s make it simpler if all the askers did it like this.