要求:输入一个字符串,统计字符串中每个字符出现的次数
import java.util.HashMap;
import java.util.Scanner;
import java.util.Set;
public class Demo {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入需要检测的字符串:");
String s = sc.nextLine();
HashMap<Character,Integer> hm = new HashMap<Character,Integer>();
for(int i=0;i<s.length();i++){
Character key = s.charAt(i);
Integer value =hm.get(key);
if(value ==null){
hm.put(key,1);
}
else{
value++;
hm.put(key,value);
}
}
Set<Character> keySet = hm.keySet();
for(Character key:keySet){
Integer value = hm.get(key);
System.out.println(key +","+value);
}
}
}
运行结果