您能否向我解释一下如何将此 for 循环更改为递归我知道什么是递归,但我无法使用代码正确打印星星的数量,因为它只打印第一行星星。
任何指导将不胜感激,
这是我当前的代码:
static void printLine(int n) {
for (int i=0; i<n; ++i) {
System.out.print("*");
}
System.out.println();
}
最佳答案
谷歌搜索“如何将 for 循环转换为递归”,有一个类似的答案 here ,以及一篇带有示例的文章 here .
这是一个相当大的提示,但基本思想是您的参数存储当前循环状态。
for (int i = 1; i <= n; i++)
{
// ....
}
相当于:
private static void PerformAction(int n)
{
if (n > 0)
{
// Do something
PerformAction(n - 1);
}
}
关于java - 将 For 循环更改为递归方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40137027/