public class test19 {
public static void main(String[] args) {
HashMap<Character, Integer> hm = new HashMap<>();
ArrayList<String> list = new ArrayList<>();
Collections.addAll(list, "abc", "bcd");
//int count =1;
// int count2 = 0;
for (String s : list) {
char[] ch = s.toCharArray();
for (char c : ch) {
if (!hm.containsKey(c)) {
hm.put(c, 1);//hm.put(c,count);
} else {
hm.put(c, hm.get(c) + 1);//count2 = hm.get(c) + 1;
} //hm.put(c, count2);
}
}
//System.out.println(hm);
Set<Entry<Character, Integer>> entry = hm.entrySet();
for (Entry<Character, Integer> e : entry) {
char c = e.getKey();
int a = e.getValue();
System.out.println("字符" + c + "出现了" + a + "次");
}
}
}
这段代码主要是求字符串中的字符出现的次数,代码中被注释掉的部分是我之前写的,不明白为什么改成注释掉的代码程序运行出现的次数就是不对的,而按照现在这样做就是正确的。按照初学者的我看来都是一样,请各位大神指教一下谢谢。。。
半枯
相关分类