这里保持计数就是我想用这个程序来完成:来检查,如果一个子实例的数量相匹配实例指定金额,返回boolean值的递归方法。在递归Java方法
这是我对这个特定的递归方法的问题:我想能够移动递归方法体内的计数器,但是,我遇到了计数器在每次递归调用重置时的问题它在方法体中。我已经能够使它发挥作用的唯一途径是通过使用函数体的外部声明的静态计数器变量。是否有任何其他的技术,我可以马歇尔为了能够在宅院方法体,使这种方法可以作为一个“黑盒子”行动的方法的柜台?
感谢您的任何意见或见解可以提供。
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));
}
}
谢谢,我没有想到这种方法,但它显然是所有提出的解决方案中最优雅的。 – gryb 2012-02-05 19:37:30
@gryb不客气!减少剩余步数的方法在递归解决方案中很常见,这可能是因为递归的“结束条件”看起来更自然一些。 – dasblinkenlight 2012-02-05 20:07:08