【发布时间】:2012-02-05 04:17:38
【问题描述】:
这是我试图用这个程序完成的:一个递归方法,它检查子字符串的实例数是否与指定的实例数匹配,返回一个布尔值。
这是我在使用这种特定递归方法时遇到的问题:我希望能够在递归方法主体内移动计数器,但是,我遇到了计数器在每次递归调用时重置的问题在方法体中。我能够使其工作的唯一方法是使用在函数体外部声明的静态计数器变量。是否有任何其他技术我可以编组以便能够将方法的计数器定位在方法主体中,以便该方法可以充当“黑匣子”?
感谢您提供的任何建议或见解。
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));
}
}
【问题讨论】: