【问题标题】:Indenting an output with recursion使用递归缩进输出
【发布时间】:2020-09-22 18:50:06
【问题描述】:

我正在尝试使用递归来打印出两行文本,并且每次出现递归时都会缩进(下面的 javadoc 中的示例)。我知道使用(numCalls + 1) 将允许它每次都增加缩进,但我不确定如何实际将它放在一起,所以它要求的也是。

public class Practice1 {
/**
 * Prints 2 lines of text for each recursive call, indicating call number 
     * (a value >= 1, and <= value of numCalls, as illustrated below.  Each
     * level of recursion should be indicated by indenting the input line by
     * r spaces.  For example, if numCalls is 3, the method should print:
 *  call 1
 *   call 2
 *    call 3
 *    back 3
 *   back 2
 *  back 1
 *  @param r the level of method calls
 *  @param numCalls the number of intended levels
 */

public static void stairSteps(int r, int numCalls) {
    if (r == 0) {
        System.out.println("Done");
    } else {
        System.out.println("call " + r);
        System.out.println("back " + r);
        r--;
        numCalls++;
        stairSteps(r, numCalls);
    }
}

【问题讨论】:

    标签: java recursion


    【解决方案1】:
    public static void stairSteps(int totalLevels, int indent) {
        stairSteps(1, totalLevels, indent);
        System.out.println("Done");
    }
    
    private static void stairSteps(int level, int totalLevels, int indent) {
        if (level <= totalLevels) {
            int offs = indent * (level - 1);
            System.out.println(" ".repeat(offs) + "call " + level);
            stairSteps(level + 1, totalLevels, indent);
            System.out.println(" ".repeat(offs) + "back " + level);
        }
    }
    

    输出:

    stairSteps(3, 2);
    
    call 1
      call 2
        call 3
        back 3
      back 2
    back 1
    Done
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-06-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-12
      • 2012-05-13
      相关资源
      最近更新 更多