黑马程序员技术交流社区

标题: 字符串的字符出现次数并排序输出 [打印本页]

作者: @31415927    时间: 2016-4-27 22:30
标题: 字符串的字符出现次数并排序输出
想不通为何输出字符都是null
package com.heima.example;

import java.util.Comparator;
import java.util.HashMap;
import java.util.Scanner;
import java.util.TreeMap;

public class 排序 {

        public static void main(String[] args) {
                Scanner sc = new Scanner(System.in);
                System.out.println("请输入一个字符串");
                String s = sc.nextLine();
                char[] arr = s.toCharArray();
                TreeMap<Integer,Character> tm = new TreeMap<>(new Comparator<Integer>() {

                        @Override
                        public int compare(Integer o1, Integer o2) {
                                int num = o2.compareTo(o1);
                                return num == 0 ? 1 : num;
                        }
                });
                HashMap<Character, Integer> hm = new HashMap<>();
                for (char c : arr) {
                        hm.put(c, !hm.containsKey(c) ? 1 : hm.get(c) + 1);
                }
                for (Character ch : hm.keySet()) {
                        tm.put(hm.get(ch), ch);
                        //System.out.println(ch + "\t:\t" + hm.get(ch));
                }
                for (Integer a : tm.keySet()) {
                        System.out.println(tm.get(a) + "\t:\t" + a);
                }
        }
}




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2