這裏保持計數就是我想用這個程序來完成:來檢查,如果一個子實例的數量相匹配實例指定金額,返回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