简体   繁体   中英

StackOverflowError in Recursive Method

I'm trying have a recursive method count how many instance the letter "e" appears in a given string. My test string is Count my e's please! . Here is the code so far:

public static int showE(String s, int count, int index)
{
        if (index == -1) return count;
        String e = "e";
        int i = s.indexOf(e, index);
        if (i != -1) count ++;
        return showE(s, count, i);
}

When I debugged the code, int i would remain at 9 instead of increasing through each call.

I thought that since that last line of code used int i as input, it would set int index in the method's signature to 9, 15, and 18 through each call for the test string. Once the letter e was no longer detected, I thought that int i would send -1 to to the signature, and then int count would be returned back to the main method. However, debugging showed that int i would be set to 9 through each call leading to a StackOverflowError. How can fix this?

edit: This is the code in response to Stephen C. Sorry about the formatting:

public static int showE(int count, int index)
{
        String e = "e";
        index = s.indexOf(e, 0)
        for(int i = index; i = < s.length() - 1; i++)
        {
            if (index == e) count++;
        }
        return count;
}

String.indexOf starts searching at the index you provide. So it starts searching at index 9, and finds an 'e' there, so returns 9.

Try starting indexOf at index + 1 .

Two points:

  • There is a more elegant recursive solution to this problem that only requires 2 arguments in the showE method. Hint: think of adding something to the result of the recursive call ...

  • Recursive solutions to problems in Java have an inherent problem. Java stacks are always finite, and Java doesn't implement tail-call optimization. Combine these two, and it is inevitable that any problem that requires really deep recursion will lead to a stack overflow.

    In this case, this means that if you try to count the E's in a long enough string, you will get an exception ... even if you get the recursion correct.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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