简体   繁体   English

递归打印方法

[英]Recursive Print Method

I'm trying to print following pattern:我正在尝试打印以下模式:

0
11
0
222
0
3333
0
222
0
11
0

I want to achieve this by using recursion and a loop inside said recursive method, which gets one integer value passed.我想通过在所述递归方法中使用递归和循环来实现这一点,该方法获得一个 integer 值传递。 The int value determines how far this pyramid pattern goes. int 值决定了这个金字塔模式走多远。 In the example above the int value would be 3. I managed to get the bottom half, but I have no idea to get the upper half.在上面的示例中,int 值将是 3。我设法得到了下半部分,但我不知道得到上半部分。

if (arg != 0) {
            System.out.println("0");
            for (int i = 0; i <= arg; i++) {
                System.out.print(arg);
            }
            System.out.println();
            print(arg - 1);
        }

How would I be able to somehow implement some increment, which turns to a decrement to this recursion?我如何能够以某种方式实现一些增量,从而减少此递归? Since I'm thinking this would be how I could achieve the above pattern.因为我认为这就是我实现上述模式的方式。

Thank you very much in advance!非常感谢您!

You can pass two arguments.您可以通过两个 arguments。 The Max value and start value which will be zero and最大值和起始值将为零,并且

then increment start value until reaches max然后增加起始值直到达到最大值

then decrement Max until reaches zero然后递减 Max 直到达到零

call --> printline(3);调用--> printline(3);

  private static void printline(int input,  int... vars) {
        if (input == 0) {
            System.out.println(0);
            return;
        }
        int start= vars.length > 0 ? vars[0] : 0;
        start++;
        System.out.println("0");
        for (int i = 0; (i <= start && i <= input); i++) {
            System.out.print(start >= input ? input : start);
        }
        System.out.println();
        if (start >= input) {
            input--;
        }

        printline(input, start);

    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM