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.

6
  • 1
    Pointing in right direction: What is a debugger and how can it help me diagnose problems? Commented Jan 31, 2020 at 3: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. Commented Jan 31, 2020 at 3:13
  • 1
    FYI: Down-voted for not attempting to debug your own code before asking us to debug it for you. Commented Jan 31, 2020 at 3:15
  • Alright thank you for your help. I will be sure to debug in the future before coming here, I apologize. Commented Jan 31, 2020 at 3: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.. Commented Jan 31, 2020 at 3:19

1 Answer 1

1

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

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

if (index + 2 > letters.length) {
    return 0;
}
...
Sign up to request clarification or add additional context in comments.

3 Comments

I get that I was missing my base case now, but it is now just returning 0 every time
I guess now you need to debug.
It was a simple mistake: forgot to add the smileCounter value of each method call to the next. Can't thank you guys enough for your help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.