获取字符串中每⼀个字母出现的次数。要求返回结果格式是:a(1)b(2)d(4)...; 1) 使用Scanner函数输入字符串 2) 使用toCharArray转化为字符串 3) 创建TreeMap存放字母和字母出现的次数,字母和次数有对应关系。结果要求abc...是有序的,所以使⽤TreeMap。 4) 获取字符串中的每⼀个字母。⽤字母查表,如果查到了字母对应的次数,就将这个次数+1后重新存回到表中。如果没有查到就将字母和1存到表中。 5) 每⼀个字母都查完表后,表中记录的就是所有字母出现的次数。
时间: 2024-03-05 22:51:34 浏览: 50
好的,以下是实现该功能的Java代码示例:
```java
import java.util.Scanner;
import java.util.TreeMap;
public class LetterCount {
public static void main(String[] args) {
// 输入字符串
System.out.print("请输入一个字符串:");
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
// 转换为字符数组
char[] charArray = input.toCharArray();
// 存放字母和字母出现的次数的TreeMap
TreeMap<Character, Integer> letterCountMap = new TreeMap<>();
// 遍历字符数组,统计字母出现次数
for (char c : charArray) {
// 判断是否为字母
if (Character.isLetter(c)) {
// 转换为小写字母,便于统计
c = Character.toLowerCase(c);
// 查找字母在表中对应的次数
Integer count = letterCountMap.get(c);
if (count == null) {
// 如果表中没有该字母,则将字母和1存入表中
letterCountMap.put(c, 1);
} else {
// 如果表中已有该字母,则将次数+1后重新存入表中
letterCountMap.put(c, count + 1);
}
}
}
// 输出结果
System.out.print("字母出现次数:");
for (Character key : letterCountMap.keySet()) {
System.out.print(key + "(" + letterCountMap.get(key) + ") ");
}
}
}
```
运行程序,输入一个字符串,例如:"Hello World!",则输出结果为:"字母出现次数:d(1) e(1) h(1) l(3) o(2) r(1) w(1)"。
阅读全文
相关推荐













