统计一个字符串中每个字符出现次数。
实现步骤:
1.创建Scanner对象
2.获取键盘录入的字符串
3.创建Map集合对象,键:Character,值:Integer
4.遍历字符串(1.toCharArray() 2.for+charAt(int index))
5.获取当前字符,保存到Character类型变量ch中
6.Map集合对象调用containsKey方法,传递变量ch作为键,获取结果(boolean类型)
7.判断如果containsKey方法结果是false,说明ch作为键,没有被存储过
8.Map集合对象调用put方法,存储键值对ch作为键1作为值
9.判断如果containsKey方法结果是true,说明ch作为键,被存储过
10.Map集合对象调用get方法,ch作为键获取值(表示已经出现的次数)保存int变量count中
11.把count值+1
12.Map集合对象调用put方法,存储键值对ch作为键count作为值
13.遍历打印输出Map集合对象
public class Demo01MapCount {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入一个字符串: ");
String str = sc.nextLine();
Map<Character,Integer> map = new HashMap<>();
for(int i = 0;i<str.length();i++) {
char ch = str.charAt(i);
boolean result = map.containsKey(ch);
if(!result) {
map.put(ch,1);
} else {
int count = map.get(ch);
count++;
map.put(ch,count);
}
}
System.out.println(map);
}
}