递归深度 - 标签& Java中的凹痕 [英] Recursion depth - tabs & dents in Java

查看:161
本文介绍了递归深度 - 标签& Java中的凹痕的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想格式化我的Java程序的输出,以便我可以看到递归是多深。怎么做?
在递归树中不会迷路的真正重要。

示例输出(从0开始计算第n个数的平凡递归函数):

 这是第一次递归调用。输入值:3. 
这是第二次递归调用。输入值:2.
这是第3次递归调用。输入值:1.
输出值:1.
这又是第二次递归调用。输入值:2.
输出值:1 + 1.
这又是第一次递归调用。输入值:3.
输出值:1 + 1 + 1.


解决方案

你可以使用一个表示你有多深的变量(比如 level )。它从1开始,在递归调用时递增。

  public static void main(String [] args){
函数(3,1);


public static String function(int input,int level){
String tab =;
for(int i = 0; i tab + =\t;
}
System.out.println(tab +这是+ level +递归调用,输入值:+ input);
if(input == 1){
System.out.println(tab +Output value:1);
返回1;
}
字符串输出=函数(输入 - 1,级别+ 1);
System.out.println(tab +这又是+ level +递归调用,输入值:+ input);
System.out.println(tab +输出值:+输出++ 1);
返回输出++ 1;
}


I want to format my output of a Java program so that I can see "how deep" the recursion is. How to do it? It is really important not to get lost in my recursion tree.

Example output (trivial recursion function for counting the nth number from 0):

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.

解决方案

You can use a variable (like level) that represents how deep you are. It starts at 1 and it increments at each recursive call.

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";
}

这篇关于递归深度 - 标签&amp; Java中的凹痕的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆