【发布时间】:2018-03-27 05:44:25
【问题描述】:
我正在实现一个代码,用于计算字符串中所有字符的出现次数。我使用 indexOf() 方法来检查事件。但它不适用于第一个角色。 以下代码适用于除第一个字符之外的所有字符。
public static void main(String[] args) {
String str = "simultaneously";
int[] count = new int[str.length()]; //counter array
for (int i = 0; i < count.length; i++) { //initializing counters
count[i] = 0;
}
for (int i = 0; i < str.length(); i++) {
int index = -1;
char c = str.charAt(i);
while (1 > 0) {
if (str.indexOf(c,index) > 0) { //This is not working for
//the first characters
index = str.indexOf(c, index) + 1;
count[i]++;
} else {
break;
}
}
}
for (int i = 0; i < count.length; i++) {
System.out.println(str.charAt(i) + " occurs " + count[i] + " times");
}
}
【问题讨论】:
-
条件
while (1 > 0)最好写成while(true) -
无需将数组元素初始化为零:Java按规范将新数组的元素初始化为默认值,int的默认值为零。