使用 Map 集合,实现输入一个字符串,计算每个字符的次数。
输入一个字符串,计算每个字符串的次数。
public class Test {
public static void main(String[] args) {
System.out.println("嗨客网(www.haicoder.net)\n");
LinkedHashMap<Character,Integer> map = new LinkedHashMap<>();
Scanner sc = new Scanner(System.in);
System.out.println("请输入一个字符串:");
String str = sc.nextLine();
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
// 如果map中有key值
if(map.containsKey(ch)){
// map中的value加一
Integer oldCount = map.get(ch);
map.put(ch,oldCount+1);
}else{
map.put(ch,1);
}
}
System.out.println(map);
}
}
运行结果如下图:
以上案例实现输入一个字符串,计算每个字符串的次数。