[Solved] What’s wrong in my code to find character frequency?


There isn’t any preventive measure in your code that enables the code not to count same chracter in the feature steps. Here I just modified your code to make it work correctly. But you can compare it with other version I provided to prevent double counting.

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);
}
}

Output:

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

1

solved What’s wrong in my code to find character frequency?