Keeping count in a recursive Java method
You are almost there: you should change the meaning of the check
variable to the remaining number of matches, rather than the original number requested. Then you can rewrite the method without keeping an additional count at all, as follows:
public static boolean copies(String whole, String part, int check)
{
//check if current string length is valid
if(whole.length() < part.length())
{
//check if check parameter equals part instances
if(check == 0)
{
return true;
}
else
{
return false;
}
}
//check if current string value is an instance of part
if(whole.substring(0, 3).equals(part))
{
check--;
}
return return copies(whole.substring(1), part, check);
}
gryb
Updated on November 04, 2020Comments
-
gryb over 3 years
Here's what I'm trying to accomplish with this program: a recursive method that checks if the number of instances of a substring matches a specified amount of instances, returning a boolean.
Here's the issue I'm having with this particular recursive method: I'd like to be able to move the counter inside the recursive method body, however, I ran into the issue that the counter resets at each recursive call when it is in the method body. The only way I have been able to make it work is through the use of a static counter variable declared outside of the function body. Is there any other technique I can marshall in order to be able to situate the counter of the method in the method body so that this method may act as a "black box"?
Thanks for any advice or insights you can provide.
public class strCopies { //count instances of part and whole equality static int count = 0; public static boolean copies(String whole, String part, int check) { //check if current string length is valid if(whole.length() < part.length()) { //check if check parameter equals part instances if(count == check) { return true; } else { return false; } } //check if current string value is an instance of part if(whole.substring(0, 3).equals(part)) { count++; } //recursive call return copies(whole.substring(1), part, check); } public static void main(String[] args) { System.out.println(copies("dogcatdog", "cat", 2)); } }