java - 直接递归 printStars
问题描述
public static void printStars(int lines) {
int j;
if(lines>0) {
for(j=0;j<lines;j++) {
System.out.print("*");
}
System.out.println();
printStars(lines -1);
for(j=0;j<lines;j++) {
System.out.print("*");
}
System.out.println();
}
}
我试图了解第二个 for 循环是如何工作的。据我了解,第一个循环将运行直到j
小于,3
并且该方法将调用自身并且您将得到。lines==2
并为最后一次通话打印两颗星和打印1
星。
***
**
*
但是对于第二个 for 循环,为什么要打印
*
**
***
如果(lines-1)==2
,不应该吗?
**
*
仅通过移动递归语句的顺序,代码会发生如此大的变化,是否有一些特殊的原因?
解决方案
将调用堆栈显示为缩进:
call to printStars(3):
prints "***"
call to printStars(2):
prints "**"
call to printStars(1):
prints "*"
call to printStars(0):
does nothing
end of call
prints "*"
end of call
prints "**"
end of call
prints "***"
end of call
推荐阅读
- wordpress - Wordpress,带有自定义链接的 slug 术语的回显列表
- xslt - 如何格式化右侧带有减号的数字?
- javascript - 增加中心滑块宽度的滑块。(滑块插件建议)
- python - 从特定行之间的文件中提取一部分
- python - 将 MATLAB 的“fminsearch”及其约束转换为 scipy 的“最小化”
- wso2esb - 如何从 wso2 esb 中的现有 .text 文件中添加额外的列?
- ios - ios swift 4可见部分视图上的触摸事件
- python - 用 Tkinter 等待一定的时间
- angular - 无法匹配Angular中的路线
- db2 - 缺少 DB2 版本 10 percentile_CONT