需求:
键盘录入一个字符串,统计每个元素出现的次数;
输入:sadalhfeofhewvjnkvbcxnmcioqw
输出:a[2]b[1]c[2]d[1]e[2]f[2]h[2]i[1]j[1]k[1]l[1]m[1]n[2]o[2]q[1]s[1]v[2]w[2]x[1]
代码实现:
import java.util.Arrays;
import java.util.HashMap;
import java.util.Scanner;
import java.util.Set;
public class Tongji1 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
HashMap<Character,Integer> map = new HashMap<>();
StringBuilder stringBuilder = new StringBuilder();
String s = scanner.nextLine();
for (int i = 0; i <s.length() ; i++) {
char c = s.charAt(i);
Integer integer = map.get(c);
if(integer==null)
{
map.put(c,1);
}else
{
integer++;
map.put(c,integer);
}
}
Set<Character> characters = map.keySet();
for (Character h:characters
) {
Integer integer = map.get(h);
stringBuilder.append(h).append("[").append(integer).append("]");
}
String s1 = stringBuilder.toString();
System.out.println(s1);
}
}