短语中出现的字母

时间:2012-12-05 20:47:30

标签: java string

我收到以下错误:

  

线程“main”中的异常java.lang.NullPointerException at   HashMap.CountLetters.tallyPrint(CountLetters.java:12)at   HashMap.CountLetters.main(CountLetters.java:21)

目标是在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"));
    }
}

3 个答案:

答案 0 :(得分:2)

fav.put("" + phrase.substring(i,i+1), fav.get(phrase)+1)

子表达式

fav.get(phrase)

应该是

fav.get(phrase.substring(i,i+1))

您正在尝试增加计数,但是您没有获得先前的值来添加1,而是获得了不相关键的值,因此您得到NullPointerException尝试自动取消装箱nullint

答案 1 :(得分:1)

你需要在这里使用charAt()而不是子字符串,因为当你试图读取地址1以上的字符时,它会给出NPE

完整代码

import java.util.HashMap;

public class CountLetters {
    public HashMap tallyPrint(String phrase) {
        int count = 0;
        HashMap<Character, Integer> fav = new HashMap<Character, Integer>();
        for (int i = 0; i<phrase.length(); i++) {
            if (fav.containsKey(phrase.charAt(i))) 
                fav.put(phrase.charAt(i), (fav.get(phrase.charAt(i)))+1);
            else
                fav.put(phrase.charAt(i),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"));
    }
}

输出

  

{f = 1,= 6,d = 1,e = 4,a = 1,n = 3,o = 1,l = 2,m = 3,u = 1,t = 1,s = 3 ,r = 1,y = 2}

答案 2 :(得分:0)

替换 fav.put("" + phrase.substring(i,i+1), fav.get(phrase)+1);

使用:

fav.put("" + phrase.substring(i,i+1), fav.get(phrase.substring(i,i+1))+1);

附注1:您应该提取substring并将其存储在临时变量中以提高效率,这样您就不会为同一个子字符串反复调用substring

附注2:感谢您在问题中发布整个(使用主要方法)。如果所有的人都这样做,那就更简单了。