黑马程序员技术交流社区

标题: 是大神的请过来看看,百撕不得骑姐 [打印本页]

作者: 子若    时间: 2016-4-27 00:18
标题: 是大神的请过来看看,百撕不得骑姐
程序如下:
public static void main(String[] args) {
                Scanner sc = new Scanner(System.in);
                System.out.println("请输入一串字符串:");
                String line = sc.nextLine();
                char[] arr = line.toCharArray();
                Map<Character, Integer> map = new HashMap<Character, Integer>();
                for (char c :arr ) {
                        if (map.containsKey(c)) {
                                map.put(c, map.get(c)+1);
                        }else{
                                map.put(c, 1);
                        }
                }
               
               
                TreeMap<Integer, Character> tm = new TreeMap<>(new Comparator<Integer>() {
                        @Override
                        public int compare(Integer i1,Integer i2){
                                int num = i2 - i1;
                                return num == 0 ? 1 : num;
                        }
                });
               
                for (Character c : map.keySet()) {
                        tm.put(map.get(c), c);
                }
                System.out.println(tm);
               
               
                for (Integer key : tm.keySet()) {
                        System.out.println(tm.get(key) + "=" + key);
                }
               
        }
运行结果如下:
请输入一串字符串:
aaabbbbcccccccddddddeeeeeeeeee
{10=e, 7=c, 6=d, 4=b, 3=a}
null=10
null=7
null=6
null=4
null=3

请问为什么遍历时候打印的都是null?

作者: yunmu    时间: 2016-4-27 11:12
建议打上注释,要不然基本没人会看没注释的代码题,我也没心情....只能说在第一个for循环结束后,补上 for (Character key : map.keySet()) {                                     System.out.println(key+"--"+map.get(key));                             }就行了,后边的全部没用
作者: 子若    时间: 2016-4-27 23:09





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