java - 我的递归方法无法正确返回 char 出现的总数

标签 java arrays loops recursion methods

{
    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...我尝试过以各种方式调整它,但我已经没有想法了。我在递归方面还是个新手。

最佳答案

应该坚持使用简单的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;
}

关于java - 我的递归方法无法正确返回 char 出现的总数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29045114/

相关文章:

java - 如何在 Java 中克隆 JInternalFrame?

linux - 无法使用变量扩展名在 bash 循环中分配正确的文件名

java - Axis Web 服务保持 Activity 状态

javascript - 如何在javascript中创建数组作为属性?

arrays - 已排序矩阵中的第 K 个最小元素

php - 如何在 php 中执行许多 curl 请求时实践良好的道德规范

java - 接口(interface)和参数多态性

java - JDBC4 和 Class.forName

java - CyclicBarrier:导致屏障跳闸的 'x' 个线程中的 'y' 完成执行并终止