案例题:计算一个字符串中每个字符出现的次数
案例分析图:

代码:
public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("输入一个字符串"); String next = sc.nextLine(); char[] chars = next.toCharArray(); Arrays.sort(chars); HashMap<Character, Integer> map = new HashMap<>(); for (char aChar : chars) { if (map.containsKey(aChar)) { Integer value = map.get(aChar); value++; map.put(aChar,value); }else{ map.put(aChar,1); } } System.out.println(map); }
运行结果:

Scanner sc = new Scanner(System.in);
System.out.println("输入一个字符串");
String next = sc.nextLine();
char[] chars = next.toCharArray();
Arrays.sort(chars);
HashMap<Character, Integer> map = new HashMap<>();
for (char aChar : chars) {
if (map.containsKey(aChar)) {
Integer value = map.get(aChar);
value++;
map.put(aChar,value);
}else{
map.put(aChar,1);
}
}
System.out.println(map);
}

浙公网安备 33010602011771号