在控制台输入一句英语, 获得每个字母出现的次数,注:每个字符作为key,出现的次数作为value

public class TestDemo1 {
    public static void main(String[] args) {
        HashMap<Character,Integer> hashMap = new HashMap();
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入一英语:");
        String s = scanner.nextLine();
        String regex = "[a-zA-Z ,.]*";
        boolean b = s.matches(regex);
        if (!b){
            System.out.println("你的输入有误");
            return;
        }
        //除去空格逗号句号
        String s1 = s.replaceAll("[ ,.]", "");
        //遍历字符串
        for (int i = 0; i < s1.length(); i++) {
            int value = 1;
            //得到集合的Key
            Set keySet = hashMap.keySet();
            char c = s1.charAt(i);
            //判断集合是否为空
            if(keySet==null){
                hashMap.put(c,value);
                continue;
                //如果Keyset中已经存在当前字母则将它的Value取出来加一再放进去
            }else if(keySet.contains(c)){
                int i1 = hashMap.get(c);
                i1++;
                hashMap.put(c, i1);
                continue;
            }else {
                hashMap.put(c,value);
            }
        }
        System.out.println(hashMap.toString());

    }
}

小编是还没入门的菜鸟求大神更优化的代码

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值