Files
javaSE-0113/javaSE-day04/src/com/inmind/map01/Test05.java

49 lines
1.9 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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<Character, Integer> 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<Map.Entry<Character, Integer>> entries = map.entrySet();
for (Map.Entry<Character, Integer> entry : entries) {
System.out.println("字符"+entry.getKey()+"出现的次数为"+entry.getValue());
}
}
}