2 回答

TA貢獻1820條經驗 獲得超9個贊
每次經過循環時,您都會將 i 增加兩次。因此,您只測試其他所有字符。在循環內使用 continue 而不是 i++。
public static void solution(String s) {
char[] c = s.toCharArray();
int j = 0, i = 0, counter = 0;
for(i = 1; i < c.length; i++) {
if(c[i] != c[j]) {
continue;
} else {
counter++;
}
}
System.out.println("The letter " + c[j] + " appears " + counter + " times");
}
請注意,此代碼將告訴您字符串中的第一個字符出現在字符串的其余部分中的次數。也許這就是您想要的,但您的問題并不清楚。

TA貢獻1797條經驗 獲得超4個贊
您的代碼中沒有任何預防措施使代碼在功能步驟中不計算相同的字符。在這里,我只是修改了您的代碼以使其正常工作。但是您可以將它與我提供的其他版本進行比較,以防止重復計算。
public class Main {
public static void solution(String s) {
char[] c = s.toCharArray();
int j = 0, i = 0, counter = 0;
for (i = 0; i < c.length; i++) {
for (j = i; j < c.length; j++) {
if (c[i] == c[j]) {
counter++;
}
}
System.out.println("The letter " + c[i] + " appears " + counter + " times");
counter = 0;
}
}
public static void main(String args[]) {
String s = "abaababcdelkm";
solution(s);
}
}
輸出:
The letter a appears 4 times
The letter b appears 3 times
The letter a appears 3 times
The letter a appears 2 times
The letter b appears 2 times
The letter a appears 1 times
The letter b appears 1 times
The letter c appears 1 times
The letter d appears 1 times
The letter e appears 1 times
The letter l appears 1 times
The letter k appears 1 times
The letter m appears 1 times
添加回答
舉報