public class Demo33 { public static void main(String[] args) { MyScanner(); } public static void MyScanner() { //设置从键盘录入. Scanner s = new Scanner(System.in); while(true) { String str = s.nextLine(); if(str.equals("over")) { System.out.println("输入结束"); break; } else { char[] ch = str.toCharArray(); ListArray(ch); //获取到该字符串的字符数组, } } } public static void ListArray(char[] ch) { //遍历该字符数组,将字符和对应出现次数存入map集合. Map<Character,Integer> ma = new HashMap<Character,Integer>(); for(int x = 0; x < ch.length ; x ++) { int n = 0; for(int y = 0; y < ch.length; y ++) { if(ch[x] == ch[y]) { n ++; } } if(ma.containsKey(ch[x])) { continue; }else { ma.put(ch[x], n ); } } ListMap(ma); //将map作为参数传递. } public static void ListMap(Map<Character, Integer> ma) { //遍历map集合,并获取value值. Set<Entry<Character,Integer>> se = new HashSet<Entry<Character,Integer>>(); int[] in = new int[ma.size()]; //创建一个和map元素数相同的数组. se = ma.entrySet(); Iterator<Entry<Character,Integer>> it = se.iterator(); int n = 0; while(it.hasNext()) { Entry en = it.next(); in[n] = (Integer) en.getValue(); //将value值存入int数组. n ++; } Arrays.sort(in); //排序数组. int num = 0; System.out.println(Arrays.toString(in)); for(int x = in.length -1, y = 26; x >= 0; x --, y --) //倒着赋值. { num += in[x]* y; //累加. } System.out.println(num); //将结果打印. } } |