0

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.

E_net4
  • 27,810
  • 13
  • 101
  • 139
  • 1
    Pointing in right direction: [What is a debugger and how can it help me diagnose problems?](https://stackoverflow.com/q/25385173/5221149) – Andreas Jan 31 '20 at 03:12
  • 3
    *Hint:* Your stop condition is `letters.length < 2`, but `letters.length` never changes, so it'll never be true. Perhaps you should include the changing value (`index`) in the stop condition, somehow. – Andreas Jan 31 '20 at 03:13
  • 1
    *FYI:* Down-voted for not attempting to **debug** your own code before asking us to debug it for you. – Andreas Jan 31 '20 at 03:15
  • Alright thank you for your help. I will be sure to debug in the future before coming here, I apologize. – Brandon Bischoff Jan 31 '20 at 03:16
  • 1
    *"it doesn't seem that the index I am trying to access (0) is negative nor greater than the provided array"* The error occurs when `index = 7`, i.e. **equal** to the length of the array.. – Andreas Jan 31 '20 at 03:19
  • Thank you a lot. Your helped me figure this out. I will be sure to debug before posting here in the future. – Brandon Bischoff Jan 31 '20 at 03:45

1 Answers1

1

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

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

if (index + 2 > letters.length) {
    return 0;
}
...
DiogoSantana
  • 2,404
  • 2
  • 19
  • 24