集合练习:计算一个字符串的每个字符出现次数。

例如: aaabbccab
a 4
b 3
c 2
不能重复 可以重复
字符 统计个数
所以我们可以使用HashMap<Character,Integer> 来存储。

第一步:
使用Scanner获取用户输入的一个字符串。

第二步:
遍历字符串,获取每一个字符
String类的方法toCharArray,把字符串转换为数组,遍历数组

第三步:
使用Map集合中的方法判断获取到的字符是否已经存储到了Map集合中:
1.使用Map集合中的方法containKey(获取到的字符),返回的是boolean值。
true:字符存在
通过字符key,获取统计个数value
value++
再把新的value存储到Map中
false:字符不存在
把字符作为key,value为1存储到Map集合中

public class Test {
    
    
    public static void main(String[] args) {
    
    
        Scanner scan = new Scanner(System.in);
        System.out.println("输入一段字符串:");
        String s = scan.next();
        char []a = s.toCharArray();
        HashMap<Character,Integer> hm = new HashMap<>();
        for (char c:a) {
    
    
            if (hm.containsKey(c) == false) {
    
    
                hm.put(c,1);
            }
            if (hm.containsKey(c) == true) {
    
    
                Integer value = hm.get(c);
                value++;
                hm.put(c,value);
            }
        }
        //遍历Map集合,输出结果
        for (Character key:hm.keySet()) {
    
    
            Integer value = hm.get(key);
            System.out.println(key+"="+value);
        }
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_43573186/article/details/103374431