1.利用键盘录入,输入一个字符串 2.统计该字符串中各个字符的数量(提示:字符不用排序)


import java.util.*;

/*分析以下需求,并用代码实现
1.利用键盘录入,输入一个字符串
2.统计该字符串中各个字符的数量(提示:字符不用排序)
3.如:
用户输入字符串"If~you-want~to~change-your_fate_I_think~you~must~come-to-the-dark-horse-to-learn-java"
程序输出结果:-(9)I(2)_(3)a(7)c(2)d(1)e(6)f(2)g(1)h(4)i(1)j(1)k(2)l(1)m(2)n(4)o(8)r(4)s(2)t(8)u(4)v(1)w(1)y(3)~(6)*/
public class Test06 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("请你输入一个字符串:");
        String s = sc.nextLine();
        Map hm = new TreeMap<>();
        for (int i = 0; i < s.length(); i++) {
            char key = s.charAt(i);
           /* if(!hm.containsKey(key)){
                hm.put(key,1);
            }else{
                hm.put(key,hm.get(key)+1);
            }*/
           if(hm.get(key)==null){
               hm.put(key,1);
           }else{
               hm.put(key,hm.get(key)+1);
           }
        }
        StringBuilder sb = new StringBuilder();
        Set> entries = hm.entrySet();
        for (Map.Entry entry : entries) {
            Character key = entry.getKey();
            Integer value = entry.getValue();
            sb.append(key).append("(").append(value).append(")");
        }
        String s1 = sb.toString();
        System.out.println(s1);
    }
}

你可能感兴趣的:(代码案例)