有两个地方要改:
public static void main(String[] args)
{
System.out.println(charCount("abcabfs"));
}
public static String charCount(String str)
{
char[] chs = str.toCharArray();
TreeMap<Character, Integer> tm = new TreeMap<Character, Integer>();
for (int x = 0; x < chs.length; x++)
{
//改点1:if()里的比大小富豪全反了,改成如下所示
if (chs[x] <= 'a' && chs[x] >= 'z' || chs[x] <= 'A'&& chs[x] >= 'Z')
{
continue;
}
//改点2:chs后面忘记加[x],改成如下所示
Integer value = tm.get(chs[x]);//这里你少了一个[x]
if (value == null)
{
tm.put(chs[x], 1);
}
else
{
value = value + 1;
tm.put(chs[x], value);
}
}
// System.out.println(tm);
StringBuilder sb = new StringBuilder();
Set<Map.Entry<Character, Integer>> entryset = tm.entrySet();
for (Iterator<Map.Entry<Character, Integer>> it = entryset.iterator() ;it.hasNext();)
{
Map.Entry<Character, Integer> me = it.next();
Character ch = me.getKey();
Integer value = me.getValue();
sb.append(ch + "(" + value + ")");
}
return sb.toString();
} |