利用hashmap获取键盘输入字符串中每个字符出现的次数

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_40567229/article/details/85232731

class hello {
	public static void main(String[] args) throws ParseException {
		Scanner sc = new Scanner(System.in);
		String s = sc.nextLine();
		char[] arr = s.toCharArray();
		
		HashMap<Character, Integer> map = new HashMap<>();
		for (char c : arr) {
			if(map.containsKey(c)) {
				map.put(c,map.get(c)+1);  //如果包含这个key,就获取这个key的value并加1
			}else {
				map.put(c, 1);
			}
		}
		
		System.out.println(map);
		
}

运行结果:

猜你喜欢

转载自blog.csdn.net/weixin_40567229/article/details/85232731