I'm working through Exercise 18.10 the 10th edition of Introduction to Java Programming (Comprehensive Version), which reads as follows:
Write a recursive method that finds the number of occurrences of a specified letter in a string using the following method header:
public static int count(String str, char a)
So here's my implementation of the method:
public static int count(String str, char a)
{
if (str.charAt(str.length() - 1) != a)
return 0;
else
return 1 + count(str.substring(0, str.length()), a);
}
My base case checks whether the last character is the specified "recurring character"; if it isn't, it adds 1 to a "count" of times the character occurs in the string and recursively invokes the count method.
Running the program with this implementation in place results in a StackOverflowError. I'm guessing this is probably due to infinite recursion, and that it's this bit of code that's causing the problem:
str.substring(0, str.length())
Trouble is, I'm not totally sure I understand why. The description of the substring(int beginIndex, int endIndex) method reads
Returns a string that is a substring of this string. The substring begins at the specified beginIndex and extends to the character at index endIndex - 1.
So the way I have it written, it should return a substring that contains every character in the original string except the last character, thus removing one character of the string at a time through recursion.
I can see why there might be a problem with this in the sense that there's nothing to tell the recursion to stop when the string's length is 1 or 0, but since the problem is a StackOverflowError and not an IndexOutOfBounds exception, I'm a bit lost..