【问题标题】:Dealing with recursive method [closed]处理递归方法[关闭]
【发布时间】:2015-11-15 01:39:24
【问题描述】:

所以我在这里有一颗钻石。我现在必须以递归方式进行。我只是一个初学者,请你帮忙。递归方法对我来说有点难。

    1
   222
  33333
 4444444
555555555
 4444444
  33333
   222
    1

我使用的代码:没有递归:

 public static void main(String[] args) {
    drawNumDiamond(9);

}
public static void drawNumDiamond(int h) {
    int noofColumns= 1;
    int noofSpaces = 4;
    int start=0;
    for (int i = 1; i <= h; i++) {
        if (i<5) {
            start=i;
        } else {
            start=10-i;
        }

        for (int j = 1; j <= noofSpaces; j++) {
            System.out.print(" ");

        }
        for (int j = 1; j <= noofColumns; j++) {
            System.out.print(start);

        }
        System.out.println();
        if (i < 5) {
            noofColumns = noofColumns+2;
            noofSpaces = noofSpaces-1;
        } else {
            noofColumns = noofColumns-2;
            noofSpaces = noofSpaces + 1;
        }
    }
}

【问题讨论】:

  • "Recursive method is kinda hard for me." - 如果您至少不尝试,它可能会保持这种状态。来吧,看到你至少表现出一些尝试并不是要求太多,是吗?此外,这是本网站规则的一部分,所有与家庭作业相关的问题都应表现出善意的尝试。
  • @HovercraftFullOfEels 同意。从一个普通的菱形(1 号)开始,然后通过让该方法调用自身来尝试 3 号。大小 1 将是您的基本情况,大小 3 位将是您递归情况的开始。

标签: java recursion methods numeric


【解决方案1】:

我将简化打印菱形的迭代方式,以便可以轻松地将其扩展到递归函数。
迭代:

public static void diamond(int n){

    boolean increase = true;
    int val = 1;
    while(val > 0){
        spaces(n-val);
        printValue(2*val-1,val);
        if(val >= n) increase = false;
        if(increase) val++;
        else val--;
    }
}

private static void printValue(int times, int val) {
    for (int i = 0; i < times; i++) {
        System.out.print(val);
    }
    System.out.println();

}

private static void spaces(int times) {
    for (int i = 0; i < times; i++) {
        System.out.print(" ");
    }

}


尝试在其内部调用 diamond 方法并删除 while 循环。向其添加附加参数,以确定何时结束递归以及何时减少要打印的值。

【讨论】:

    猜你喜欢
    • 2022-09-17
    • 2015-08-25
    • 2014-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-11
    • 1970-01-01
    • 2013-08-03
    相关资源
    最近更新 更多