带有递归方法的嵌套缩进输出 [英] Nested indented output with a recursion method

查看:156
本文介绍了带有递归方法的嵌套缩进输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have an assignment to use a recursive method to print out multiple lines, each line having 3 more spaces in front of it than the previous. Here is a picture of the desired output (http://i.imgur.com/mek2QMz.png).

这是我到目前为止的代码:

This is the code I have so far:

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

我知道如何使用a来正确显示空格for-loop,但我不知道如何用递归来做这件事。

I know how to make the spaces appear correctly using a for-loop, but I have no idea how to do this with recursion.

推荐答案

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

I do this often. I have two basic methods, related:


  1. 创建一个全局字符串变量缩进,初始化为空字符串。进入该功能后,将其延长三个空格。离开时,请将其缩短到之前的长度。

  2. 添加参数缩进。初始调用是一个空字符串;每个递归将三个空格连接到值。

  1. Make a global string variable indent, initialized to the empty string. On entry to the function, lengthen it by three spaces. When you leave, shorten it to the previous length.
  2. Add a parameter indent. The initial call is with an empty string; each recursion concatenates three spaces to the value.

在每种情况下,我只使用缩进作为第一个印在线上的东西。

In each case, I just use indent as the first thing printed on the line.

这能解决你的问题吗?

这篇关于带有递归方法的嵌套缩进输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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