需求:
输入一个字符串中每个字符出现次数。
public class TestMapDemo {
public static void main(String[] args) {
//思考:
// a=3 b=5 c=100 e=3 ...
//1.创建一个保存结果Map集合
HashMap<Character,Integer> map = new HashMap<Character, Integer>();
//2.接收用户在控制台输入的字符串
System.out.println("请输入一个字符串:");
String str = new Scanner(System.in).nextLine();
//3.遍历字符串
for (int i = 0; i < str.length(); i++) {
Character ch = str.charAt(i);
//4.判断
//a.ch是第一次出现
if(!map.containsKey(ch)){
map.put(ch,1);
}else{
//b.ch已经在map中有了
Integer value = map.get(ch);
map.put(ch,value+1);
}
}
//4.打印map
System.out.println(map);
}
}