键盘录入一个字符串,统计字符串中每个字符出现的次数。
思路:看了HashMap集合之后想到了把一个字符作为键,出现的次数作为值,储存在集合中,然后遍历集合输出字符及其出现的次数。
具体操作:先遍历字符串,得到一个个字符,将每一个字符作为键到HashMap集合中去找其对应的值。如果返回值是null,说明该字符在集合中不存在,就把这个字符作为键,1作为值添加到集合中;如果返回值不是null,说明该字符在集合中存在,就将其对应的值加1,重新储存到集合中。
这样每个字符及其出现的次数就被储存在了集合中,遍历集合获取键和值,这样就得到了字符及其出现的次数。
下面是代码:
import java.util.HashMap;
import java.util.Scanner;
import java.util.Set;
public class stringStatistics {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入一个字符串:");
String line = sc.nextLine();
HashMap<Character, Integer> hm = new HashMap<Character, Integer>();
for (int i = 0; i < line.length(); i++) {
Character key = line.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) {
System.out.println(key + "出现" + hm.get(key) + "次");
}
}
}
下面是演示截图: