samedi 20 avril 2019

If statement in nested for loops aren't running the amount of times they should be

I apologise beforehand, I'm a java novice! This is a method to output the frequency of characters in a String in alphabetical order.

public static int[] charCount(String s) {
    if (s == null) {
        throw new IllegalArgumentException("Null");
    }

    ArrayList<String> count = new ArrayList<String>();
    String[] sArr = s.split("");
    for (int i = 0; i < sArr.length; i++) {
        if (!(count.contains(sArr[i]))) {
            count.add(sArr[i]);
        }
    }

    Collections.sort(count);

    int[] result = new int[count.size()];

    for (int i = 0; i < count.size(); i++) {
        int cCount = 0;
        for (int j = 0; j < sArr.length; j++) {
            if (sArr[j] == count.get(i)) {
                cCount++;
            }
        }
        result[i] = cCount;
    }

return result;
}   

No matter what String is passed to it, the output array will only contain 1's. The if statement in the nested for loop seems to stop running after cCount is incremented once. Help please!

Aucun commentaire:

Enregistrer un commentaire