首页 > 解决方案 > 数组索引越界 - Java 递归方法

问题描述

我正在用 3 种不同的方法编写一个程序来练习递归。我已经成功实施了三个中的一个,但我现在有点卡在第二个上。此方法尝试计算字符数组中“微笑”(:)) 的数量。我以为我写得对,但是当我测试它时,我不断收到 ArrayIndexOutOfBoundsException,但我不知道为什么。我的方法如下:

public static int countSmiles(char[] letters, int index) {

    int smileCounter = 0;

    //If the array is less than 2 in length it cannot include ":)".
    if(letters.length < 2) {
        return 0;
    }

    //If there is a smile increment the counter.
    else if(letters[index] == ':') {
        if(letters[index+1] == ')') {
            smileCounter++;
        }
    }

    //Increment the index
    index++;

    //Recursive assignment
    smileCounter = countSmiles(letters, index);

    //Return number of smiles
    return smileCounter;

}

我正在测试的方法如下:

public static void main(String[] args) {

    char[] JavaCharArray = {'r', 's', 't', 'u', ':', ')', 'v'};
    System.out.println(countSmiles(JavaCharArray, 0));
}

从我的代码来看,我尝试访问的索引 (0) 似乎不是负数,也不大于提供的数组。我真的只是不明白。

标签: javaarraysrecursionindexoutofboundsexception

解决方案


在递归方法中,您需要一个停止条件。尝试:

...
if(letters.length < 2) {
    return 0;
}

if (index + 2 > letters.length) {
    return 0;
}
...

推荐阅读