【问题标题】:Nested indented output with a recursion method使用递归方法嵌套缩进输出
【发布时间】:2017-04-06 00:20:03
【问题描述】:

我有一个任务是使用递归方法打印出多行,每行前面的空格比前一行多 3 个。这是所需输出的图片 (http://i.imgur.com/mek2QMz.png)。

这是我目前的代码:

public class Prog6d {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int input = scan.nextInt();
        System.out.println(printFactorial(input));
    }

    //Calculates the factorial
    public static int printFactorial(int input) {
        if (input == 1) {
            return 1;
        }
        System.out.println("factorial(" + input + ")");
        System.out.print("   ");
        return input*printFactorial(input-1);
    }
}

我知道如何使用 for 循环使空格正确显示,但我不知道如何使用递归来做到这一点。

【问题讨论】:

    标签: java recursion


    【解决方案1】:

    我经常这样做。我有两种基本方法,相关:

    1. 创建一个全局字符串变量indent,初始化为空字符串。在进入函数时,将其延长三个空格。离开时,将其缩短到之前的长度。
    2. 添加参数缩进。初始调用是一个空字符串;每个递归将三个空格连接到值。

    在每种情况下,我只使用 indent 作为第一行打印的内容。

    这能解决你的问题吗?

    【讨论】:

    • 我会推荐第二种方法而不是第一种方法,因为如果您避免使用全局变量,您将在调试程序时省去很多麻烦。如果您将调用进行尾递归,则参数化版本应该同样有效。
    猜你喜欢
    • 1970-01-01
    • 2018-02-04
    • 2017-07-08
    • 2018-05-28
    • 1970-01-01
    • 2012-01-07
    • 1970-01-01
    • 2020-01-14
    • 1970-01-01
    相关资源
    最近更新 更多