简体   繁体   English

数组索引越界 - Java 递归方法

[英]Array Index Out Of Bounds - Java Recursive Method

I am writing a program with 3 different methods to practice recursion.我正在用 3 种不同的方法编写一个程序来练习递归。 I have successfully implemented one of three, but I am a little stuck on the second right now.我已经成功实施了三个中的一个,但我现在有点卡在第二个上。 This method attempts to count the number of "smiles" (:)) in a character array.此方法尝试计算字符数组中“微笑”(:)) 的数量。 I thought I had it written correctly but when I test it out I keep getting an ArrayIndexOutOfBoundsException, but I'm not sure why.我以为我写对了,但是当我测试它时,我不断收到 ArrayIndexOutOfBoundsException,但我不知道为什么。 My method is as follows:我的方法如下:

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;

}

And the method I am testing with is as follows:我正在测试的方法如下:

public static void main(String[] args) {

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

From my code it doesn't seem that the index I am trying to access (0) is negative nor greater than the provided array.从我的代码看来,我试图访问的索引 (0) 不是负数,也不是大于提供的数组。 I really just don't understand.我真的只是不明白。

In a recursive method, you need a stop condition.在递归方法中,您需要一个停止条件。 Try:尝试:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM