输入字符串统计其中每个字符的个数
public class HashDemo {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("请输入字符串:");
String str = sc.next();
char[] chars = str.toCharArray();
HashMap<Character,Integer> hm=new HashMap<>();
for (char aChar : chars) {
if (hm.containsKey(aChar)){ //如果字符出现过,那么value值加一
Integer integer = hm.get(aChar);
integer++;
hm.put(aChar,integer);
}else {
hm.put(aChar,1); //如果字符没有出现过,则将字符放入key值,同时设置value值为一
}
}
System.out.println(hm);
}
}
输出结果:
aaaabbbbbbccc
{a=4, b=6, c=3}
Process finished with exit code 0