代码如下:
import java.util.*;
public class Test {
public static void main(String []args){
String text; //存一段文本
Set keys; //存键值
Map<Character,Integer> map = new HashMap<Character, Integer>();
Scanner scn = new Scanner(System.in);
System.out.println("请输入一段文本");
text = scn.nextLine();
for(int i = 0; i < text.length(); i++){
if(map.containsKey(text.charAt(i))){ //如果该键已存在,则把值加1
map.put(text.charAt(i),map.get(text.charAt(i))+1);
}else{
map.put(text.charAt(i),1); //否则,不存在,就把该字符作为键存入map,其值为1
}
}
keys = map.keySet();
Iterator it = keys.iterator();
while(it.hasNext()){
Character x = (Character)it.next(); //把这个键存下来
System.out.println(x+":"+map.get(x)); //输出字符和个数
}
}
}