我收到以下错误:
HashMap.CountLetters.tallyPrint(CountLetters.java:12) 在 HashMap.CountLetters.main(CountLetters.java:21) 的线程“主”java.lang.NullPointerException 中的异常
目标是将每个字母的出现存储在HashMap
. 键是字母,值是出现次数。
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"));
}
}