首页 > 解决方案 > 直接递归 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,不应该吗?

**
*

仅通过移动递归语句的顺序,代码会发生如此大的变化,是否有一些特殊的原因?

标签: javarecursion

解决方案


将调用堆栈显示为缩进:

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

推荐阅读