(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)
代码示例:
package cn.zxj.com;
import java.util.Iterator;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
class Test {
public static void main(String[] args) {
System.out.println("请录入字符串并按回车键结束!");
Scanner scanner = new Scanner(System.in);
String s = scanner.next();
Map<Character, Integer> map = statisticsCn(s);
printMap(map);
}
private static void printMap(Map<Character, Integer> map) {
Set<Map.Entry<Character, Integer>> entries = map.entrySet();
Iterator<Map.Entry<Character, Integer>> iterator = entries.iterator();
while (iterator.hasNext()){
Map.Entry<Character, Integer> en = iterator.next();
System.out.print(en.getKey()+":"+en.getValue()+" ");
}
}
private static Map<Character, Integer> statisticsCn(String s) {
Map<Character, Integer> map = new ConcurrentHashMap<>();
char[] chars = s.toCharArray();
for(int i = 0;i<chars.length;i++){
if(map.containsKey(chars[i])){
Integer cn = map.get(chars[i]);
cn+=1;
map.put(chars[i],cn);
}else{
map.put(chars[i],1);
}
}
return map;
}
}