数组索引超出范围-Java递归方法

问题描述 投票:0回答:1

我正在用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)似乎不是负数也不大于提供的数组。我真的不明白。

java arrays recursion indexoutofboundsexception
1个回答
1
投票

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

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

if (index + 2 > letters.length) {
    return 0;
}
...
© www.soinside.com 2019 - 2024. All rights reserved.