diff --git a/javaSE-day04/src/com/inmind/map01/Test05.java b/javaSE-day04/src/com/inmind/map01/Test05.java new file mode 100644 index 0000000..3b0b5c6 --- /dev/null +++ b/javaSE-day04/src/com/inmind/map01/Test05.java @@ -0,0 +1,48 @@ +package com.inmind.map01; + +import java.util.HashMap; +import java.util.Map; +import java.util.Scanner; +import java.util.Set; + +/* + 7.Map练习统计字符出现的次数 + + 实现分析: + 1.使用scanner键盘输入字符串 + 2.字符串转成字符数组 + 3.创建一个键为字符类型,值为整数类型的双列集合 + 4.遍历字符数组 + 判断双列集合中是否包含指定的键,如果没有直接添加,并设置次数为1 + 判断双列集合中是否包含指定的键,如果有,在原本的次数上加1 + 5.遍历双列集合 + + */ +public class Test05 { + public static void main(String[] args) { + //1.使用scanner键盘输入字符串 + System.out.println("请输入您的字符串内容:"); + String str = new Scanner(System.in).nextLine(); + //2.字符串转成字符数组 + char[] chars = str.toCharArray(); + //3.创建一个键为字符类型,值为整数类型的双列集合 + HashMap map = new HashMap<>(); + //4.遍历字符数组 + for (char c : chars) { + if (!map.containsKey(c)) { + //判断双列集合中是否包含指定的键,如果没有直接添加,并设置次数为1 + map.put(c, 1); + } else { + //判断双列集合中是否包含指定的键,如果有,在原本的次数上加1 + /*Integer count = map.get(c);//字符原本出现的次数 + map.put(c, count + 1);*/ + map.put(c, map.get(c) + 1); + } + } + //5.遍历双列集合 + Set> entries = map.entrySet(); + for (Map.Entry entry : entries) { + System.out.println("字符"+entry.getKey()+"出现的次数为"+entry.getValue()); + } + } +}