java - 如何显示字符串中每个字母的频率?
问题描述
我希望我的代码显示每个字母的频率,但相反,我得到一个ArrayIndexOutOfBoundsException
. 我很难发现我做错了什么。
我该如何纠正这个问题?
这是我的代码:
public static void solution(String s) {
char[] c = s.toCharArray();
int j = 0, i = 0, counter = 0;
for(i = 0; i < c.length; i++) {
counter = 0;
for(j = 0; j < c.length; j++) {
if(c[j] == c[i]) {
counter++;
}
}
}
System.out.println("The letter " + c[j] + " appears " + counter + " times");
}
public static void main(String args[]) {
String s = "abaababcdelkm";
solution(s);
}
解决方案
您正在完成的循环之外访问c[j]
:它的值等于c.length
which 不是正确的索引。
您需要将println
语句上移一行并更改c[j]
为c[i]
。
我会用 Stream API 重写它:
s.chars()
.mapToObj(c -> (char)c)
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
.forEach((k, v) -> System.out.format("The letter %c appears %d times\n", k, v));
推荐阅读
- azure - Azure SQL 数据库:使用复制活动将表从一个 Azure SQL 数据库传输/迁移到另一个 Azure SQL 数据库
- apache-kafka-connect - Confluent InfluxDB 接收器连接器
- build-process - 相对“SourceCodeDirectory”项目变量文件路径在 FinalBuilder 上不起作用
- bash - 使用 Bash 和 Curl 选择工作域
- powershell - 如何使用 PowerShell 格式化分区(不是卷)?
- matlab - 使用 Matlab 编码器动态和静态分配的正确方法是什么?
- ios - 无法使用类型为“(任何?,(错误?,DatabaseReference)-> Void)”的参数列表调用“setValue”
- excel - 图表数据系列格式不正确
- react-native - 如何在本机反应中创建表格
- r - 截断和合并两个字符向量中的值