Java map计数字符串中每个字符出现的个数代码找错,我找不到错误原因,就是不能运行

//计算字符串str中每个字符出现的个数
package test1;
import java.util.HashMap;
import java.util.Map;
public class Test3 {
public static void main(String[] args) {
String str="012345678909";
Map<Character, Integer>map=new HashMap<Character, Integer>();
for(int i=0;i<str.length();i++){//字符循环
Character ch=str.charAt(i);//ch逐个存入字符
for(Character character:map.keySet()){
if(ch!=character){//添加字符
map.put(ch, 1);
}
else{//+1
int temp=map.get(ch)+1;
map.put(ch, temp);
}
}
}
System.out.println(map);
}
}

首先,你的代码是能运行的。

然后你的想法是对的,但是中间有点儿问题,所以无法得到想要的结果,第二个增强for循环里,此时的map是空的,所以你遍历map.keySet()的时候是不会执行内部循环中的操作的。

稍作修改即可:

public void test() {

String str = "012345678909";

Map<Character, Integer> map = new HashMap<Character, Integer>();

for (int i = 0; i < str.length(); i++) {// 字符循环

Character ch = str.charAt(i);// ch逐个存入字符

if(!map.keySet().contains(ch)){

map.put(ch, 1);

}else {

int temp = map.get(ch) + 1;

map.put(ch, temp);

}

}

System.out.println(map);

}

温馨提示:答案为网友推荐,仅供参考
相似回答