猿问

我的代码中查找字符频率有什么问题?

我试图输出字符串中的所有字母及其频率,但只是a出现。我认为我的逻辑是正确的,但看起来我遗漏了一些东西。


我做错了什么,我该如何解决?


这是我的代码:


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]) {

            i++;

        } else {

            counter++;

        }

    }

    System.out.println("The letter " + c[j] + " appears " + counter + " times");

}


public static void main(String args[]) {

    String s = "abaababcdelkm";

    solution(s);

}

输出:


The letter a appears 1 times


饮歌长啸
浏览 142回答 2
2回答

慕妹3146593

每次经过循环时,您都会将 i 增加两次。因此,您只测试其他所有字符。在循环内使用 continue 而不是 i++。public static void solution(String s) {&nbsp; &nbsp; char[] c = s.toCharArray();&nbsp; &nbsp; int j = 0, i = 0, counter = 0;&nbsp; &nbsp; for(i = 1; i < c.length; i++) {&nbsp; &nbsp; &nbsp; &nbsp; if(c[i] != c[j]) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; continue;&nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; counter++;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; System.out.println("The letter " + c[j] + " appears " + counter + " times");}请注意,此代码将告诉您字符串中的第一个字符出现在字符串的其余部分中的次数。也许这就是您想要的,但您的问题并不清楚。

繁星coding

您的代码中没有任何预防措施使代码在功能步骤中不计算相同的字符。在这里,我只是修改了您的代码以使其正常工作。但是您可以将它与我提供的其他版本进行比较,以防止重复计算。public class Main {public static void solution(String s) {&nbsp; &nbsp; char[] c = s.toCharArray();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; int j = 0, i = 0, counter = 0;&nbsp; &nbsp; for (i = 0; i < c.length; i++) {&nbsp; &nbsp; &nbsp; &nbsp; for (j = i; j < c.length; j++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (c[i] == c[j]) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; counter++;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; System.out.println("The letter " + c[i] + " appears " + counter + " times");&nbsp; &nbsp; &nbsp; &nbsp; counter = 0;&nbsp; &nbsp; }}public static void main(String args[]) {&nbsp; &nbsp; String s = "abaababcdelkm";&nbsp; &nbsp; solution(s);}}输出:The letter a appears 4 timesThe letter b appears 3 timesThe letter a appears 3 timesThe letter a appears 2 timesThe letter b appears 2 timesThe letter a appears 1 timesThe letter b appears 1 timesThe letter c appears 1 timesThe letter d appears 1 timesThe letter e appears 1 timesThe letter l appears 1 timesThe letter k appears 1 timesThe letter m appears 1 times
随时随地看视频慕课网APP

相关分类

Java
我要回答