Files
javaSE-260914/s-day04/src/com/inmind/map01/MapTest06.java
T

59 lines
2.1 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.遍历字符数组
判断双列集合中是否拥有某个字符为key,如果没有,直接添加,次数设置为1
判断双列集合中是否拥有某个字符为key,如果有,直接修改,次数设置为当前次数+1
5.遍历双列集合
*/
public class MapTest06 {
public static void main(String[] args) {
//1.使用scanner接收输入字符串
Scanner sc = new Scanner(System.in);
System.out.println("请输入您的内容:");
String line = sc.nextLine();
//2.字符串转字符数组
char[] chars = line.toCharArray();
//3.创建一个键为字符,值为整数的双列集合
HashMap<Character, Integer> map = new HashMap<>();
//4.遍历字符数组
for (char c : chars) {
//判断双列集合中是否拥有某个字符为key
if (map.containsKey(c)) {
//true:已经包含,那么计数就要在原本的基础上+1
/*Integer count = map.get(c);
map.put(c, count+1);*/
map.put(c, map.get(c) + 1);
} else {
//false:未包含,那么计数直接设置为1
map.put(c, 1);
}
}
//5.遍历双列集合
//5.1键找值
Set<Character> keys = map.keySet();
for (Character key : keys) {
Integer value = map.get(key);
System.out.println(key+":"+value);
}
System.out.println("------------------------------");
//5.2键值对遍历
Set<Map.Entry<Character, Integer>> entries = map.entrySet();
for (Map.Entry<Character, Integer> entry : entries) {
System.out.println(entry.getKey()+":"+entry.getValue());
}
}
}