我在临摹老师的代码时,输入了自己的数据,需求是遍历出字符串中的字母并显示出现的次数。当我在字符串中夹入了几个"^"符号的时候,竟然也跟着字母遍历出去了,难道那哥们也是字母?
代码如下:
import java.util.*;
class MapTest3
{
public static void main(String[] args)
{
String s = charCount("aabbdde.,567%^^^.....%*&*(essjj");
System.out.println(s);
}
public static String charCount(String str)
{
char[] chs = str.toCharArray();
TreeMap<Character,Integer> tm = new TreeMap<Character,Integer>();
int count = 0;
for(int x=0;x<chs.length;x++)
{
if(!(chs[x]>='a' && chs[x]<='z'|| chs[x]>='A' && chs[x]<='z'))
continue;//^为什么会出现在结果中。
Integer value = tm.get(chs[x]);
if(value!=null)
count = value;
count++;
tm.put(chs[x],count);
count = 0;
StringBuilder sb = new StringBuilder();
Set<Map.Entry<Character,Integer>> entrySet = tm.entrySet();
Iterator<Map.Entry<Character,Integer>> it = entrySet.iterator();
while(it.hasNext())
{
Map.Entry<Character,Integer> me = it.next();
Character ch = me.getKey();
Integer in = me.getValue();
sb.append(ch+"("+in+")");
}
return sb.toString();
}
}
|