As AllenKll already pointed out, the high
value should probably take the role that you intended for your index
. You have been counting the number of occurances in the high
variable, but this counting can be "hidden" in the recursion.
The purpose of these "helper" methods for recursion in general is exactly that: They usually have (at least) one additional parameter that somehow describes how far the recursion has already proceeded or how far it still has to proceed. As an example for the latter: You could also have used the high
variable as a "countdown", by writing
public static int count(char[] chars, char ch)
{
return count(chars, ch, chars.length - 1);
}
public static int count(char[] chars, char ch, int high)
{
if (high == -1)
{
return 0;
}
if (chars[high] == ch)
{
return 1 + count(chars, ch, high - 1);
}
return count(chars, ch, high - 1);
}
Of course, one could only offer the helper method. Instead of calling
count(chars, ch);
you could ask the user to call
count(chars, ch, 0);
But the problem here is that this method may be misused: When then user passes a wrong value as the last parameter, then the method will not work.
Note: This whole "helper method" thing only makes sense when the helper method is private. When it is public
, the user may still call the wrong method. I see that the public
modifier was requested in the task description, but... maybe you'll receive some bonus points when you make your instructor aware of this flaw ;-)