我的递归方法不会正确 return 一个字符出现的总数

My recursion method won't properly return the total amount of occurrences of a char

{
    char[] charArray = {'a', 'b', 'a', 'c', 'a', 'd', 'e', 'b'};
    int occurrences;

    occurrences = countOccurrence(charArray, 'a', 0);

    System.out.println("\"a\" occurred " + occurrences + " times.");
} 
public static int countOccurrence(char[] array, char character, int index)
{
    int counter = 0;
    if (index > array.length-1)
    {
        //This probably seems a little awkward...But I have this here just so it stops 
        //recursion when it hits the end of the array.
    }
    else
    {
        if (array[index] == character)
        {
            counter++;
            countOccurrence(array, character, index + 1);
        }
        else
        {
            countOccurrence(array, character, index + 1);
        }            
    }
    return counter;
}

您好,由于某些原因,当我 运行 这个程序时 'a' 出现的次数总是 1 次...我试过各种方式调整它,但我已经 运行 出主意。我还是递归的新手。

您需要将递归调用的结果添加到您的计数器中:

counter += countOccurrence(array, character, index + 1)

此外,请注意,如果 ifelse 块中的代码相同,您应该将其排除在外:

if (array[index] == character) {
    counter++;
}
counter += countOccurrence(array, character, index + 1);

使用递归执行此操作的更简洁的方法是:

static int countOccurrence(char[] array, char character, int index) {
    if (index >= array.length) {
        // base case
        return 0;
    } else {
        int foundChar = (array[index] == character) ? 1 : 0;
        return foundChar + countOcurrence(array, character, index + 1);
    }
}

应该坚持一个简单的for循环而不是混乱的递归

public static int countOccurrence(char[] array, char character)
{
    int counter = 0;
    for(int index = 0; index < array.length; ++index)
    {
        if (array[index] == character)
        {
            counter++;
        }
    }
    return counter;
}

或者,如果您热衷于使用递归:

当你的 index 达到值 array.length 时,就终止递归。

public static int countOccurrence(char[] array, char character, int index)
{
    int counter = 0;
    if (index >= array.length)
        return 0;
    if (array[index] == character)
            counter++;
    counter += countOccurrence(array, character, index + 1);
    return counter;
}