java - 递归深度 - Java 中的制表符和凹痕

标签 java recursion tabs formatting

我想格式化我的 Java 程序输出,以便我可以看到递归的“深度”。怎么做? 不要迷失在我的递归树中是非常重要的。

示例输出(用于从 0 开始计算第 n 个数字的简单递归函数):

This is the first recursive call. Input value: 3.
    This is the second recursive call. Input value: 2.
        This is the 3rd recursive call. Input value: 1.
        Output value : 1.
    This is again the second recursive call. Input value: 2.
    Output value : 1 + 1.
This is again the first recursive call. Input value: 3.
Output value : 1 + 1 + 1.

最佳答案

您可以使用代表您有多深的变量(如 level)。它从 1 开始,并在每次递归调用时递增。

public static void main(String[] args) {
    function(3, 1);
}

public static String function(int input, int level) {
    String tab = "";
    for (int i = 0; i < level - 1; i++) {
        tab += "\t";
    }
    System.out.println(tab + "This is the " + level + " recursive call. Input value: " + input);
    if (input == 1) {
        System.out.println(tab + "Output value: 1");
        return "1";
    }
    String output = function(input - 1, level + 1);
    System.out.println(tab + "This is again the " + level + " recursive call. Input value: " + input);
    System.out.println(tab + "Output value: " + output + " + 1");
    return output + " + 1";
}

关于java - 递归深度 - Java 中的制表符和凹痕,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28507978/

相关文章:

ADT合理实现的java语法帮助[错误: cannot find symbol]

java - 如何模拟无法在测试中实例化的对象?

java - 从插件写入 'Problems' 表或 'Console'

java - 如何在java中使用递归反转整数数组?

jquery - 动态创建选项卡时如何禁用重新加载?

java - Spring安全.DaoAuthenticationProvider : Cannot resolve reference to bean

algorithm - Common Lisp 中的线性递归列表差函数

python - 递归地过滤元组内的元组

android - 在选项卡之间共享一个对象(不同的 Activity )

android - 设置背景图像扰乱选项卡 Activity 中的布局