import java.util.HashMap; import java.util.Map; import java.util.Scanner; import java.util.Set; public class map_str_demo { public static void main(String[] args) { // 获取输入句柄 Scanner input = new Scanner(System.in); System.out.println("请输入一个字符串:"); // 用户输入字符串 String str = input.next(); // 创建保存字母和次数的集合 HashMap<Character, Integer> str_num = new HashMap<>(); // 遍历字符串存入集合 for (char aChar : str.toCharArray()) { // 对字符串里面的字母进行判断 if (str_num.containsKey(aChar)) { Integer value = str_num.get(aChar); str_num.put(aChar, ++value); } else { str_num.put(aChar, 1); } } // 遍历输出集合,也可以使用keySet() Set<Map.Entry<Character, Integer>> entries = str_num.entrySet(); for (Map.Entry<Character, Integer> entry : entries) { System.out.println("字母:" + entry.getKey() + "出现的次数为:" + entry.getValue() + "次!"); } } }
易错点 ++count 与count++