Java键盘输入字符串,获取字符的个数并排序

1.使用map集合

public class test01 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);//获取scanner对象
        System.out.println("请输入一个字符串:");
        String sc = scanner.next();//接收字符串
        char[] chs = sc.toCharArray();//字符串转数组
        //调用wordCount方法获取字符串
        System.out.println(wordCount(chs));

    }
    //定义处理字符串的方法
    public  static  Map<Character,Integer> wordCount(char[] chs){
          //创建集合对象
        TreeMap<Character,Integer> map = new TreeMap<>();
        for (int i = 0; i <chs.length ; i++) {//遍历数组的每个元素
            if(map.containsKey(chs[i])){//判断当前元素是否存在
                //如果存在,则在集合元素个数加1
                map.put(chs[i],map.get(chs[i])+1);
            }
            else {//否则直接把元素加到集合,元素个数为1,
                map.put(chs[i],1);
            }

            //简单的三目运算 和if -else一样
           //判断当前是否有这个值,有的化,直接在值上加1,没有的化,把元素的键加到集合map。值也加1
            //map.put(chs[i],map.containsKey(chs[i])?map.get(chs[i])+1:1);
        }return map;//返回集合
    }

}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值