黑马程序员技术交流社区

标题: 大神 帮帮忙 [打印本页]

作者: 刘永川    时间: 2016-9-15 21:17
标题: 大神 帮帮忙
键盘录入一个"aababcabcdabcde",获取字符串中每一个字母出现的次数要求结果:a(5)b(4)c(3)d(2)e(1)
有一些思路 但实现的时候有好多错误 不知道咋回事 希望有谁能帮帮我
作者: 宝瓶子    时间: 2016-9-15 21:33
public static void main(String[] args) {                 String s = "abcdekka27qoq";                 char[] ch = s.toCharArray();                                  HashMap<Character, Integer> hm = new HashMap<>();                 for (char c : ch) {                         Integer num = hm.get(c);                         if (num == null) {                                 hm.put(c, 1);                         }else {                                 hm.put(c, num + 1);                         }                                          }                 System.out.println(hm);                                  Set<Entry<Character, Integer>> entrySet = hm.entrySet();                 for (Entry<Character, Integer> entry : entrySet) {                         System.out.print(entry.getKey() + "(" + entry.getValue() + ")");                 }         }
作者: Fate_stay    时间: 2016-9-15 23:18
package cn.itcast.day21_Prictice1;

import java.util.HashMap;
public class Test {
        public static void main(String[] args) {
                String str = "aababcabcdabcde";
                // 创建一个map对象
                HashMap<Character,Integer> map = new HashMap<>();
               
                char[] ch_arr = str.toCharArray();
               
                for (char c : ch_arr) {
                        if(map.containsKey(c)) {
                                // 若已经存在字符, 则 值加1次
                                int times = map.get(c);
                                map.put(c, times+1);
                        } else {
                                // 若不存在,值:存1次
                                map.put(c,1);
                        }
                }
                method(map,'a');
                method(map,'b');
                method(map,'c');
                method(map,'d');
                method(map,'e');
        }
        public static void method(HashMap<Character,Integer> map, char c) {
                System.out.print(c+"("+map.get(c)+")");
        }
}





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