Brandon Bischoff
Brandon Bischoff

Reputation: 81

Array Index Out Of Bounds - Java Recursive Method

I am writing a program with 3 different methods to practice recursion. 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. 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. I really just don't understand.

Upvotes: 0

Views: 571

Answers (1)

DiogoSantana
DiogoSantana

Reputation: 2434

In a recursive method, you need a stop condition. Try:

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

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

Upvotes: 1

Related Questions