From cfc30feac4f23899035f14896d5e7e8322133fc0 Mon Sep 17 00:00:00 2001 From: xuxin <840198532@qq.com> Date: Tue, 3 Feb 2026 11:31:10 +0800 Subject: [PATCH] =?UTF-8?q?=E8=BF=9B=E9=98=B6day04-Map=E7=BB=83=E4=B9=A0?= =?UTF-8?q?=E7=BB=9F=E8=AE=A1=E5=AD=97=E7=AC=A6=E5=87=BA=E7=8E=B0=E7=9A=84?= =?UTF-8?q?=E6=AC=A1=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- javaSE-day04/src/com/inmind/map01/Test05.java | 48 +++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 javaSE-day04/src/com/inmind/map01/Test05.java 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()); + } + } +}