【问题标题】:How do I rewrite this method but as recursive我如何重写此方法但递归
【发布时间】:2015-09-12 22:54:01
【问题描述】:

编写一个递归方法,执行与所示方法中的循环相同的操作

public class new1 {

    public static void main(String[] args) {
        new1(4);
    }

    public static void new1(int n) {
        if (n <= 0) {
            return;
        } else {
            System.out.print("-");
            --n;
            new1(n);
            System.out.println();
            for (int x = 0; x < n; x++) {
                System.out.print("!!!");
                System.out.print("-"); // space dash space
            }
        }
    }
}

【问题讨论】:

  • 它已经是递归的了,不是吗?
  • new1(n); 是递归的。
  • 公平地说,问题是完全清楚的。这是具有误导性的标题。

标签: java for-loop recursion


【解决方案1】:

这用递归方法替换循环。

public static void main(String[] args) {
    new1(4);
}

public static void new1(int n) {
    if (n <= 0) {
        return;
    } else {
        System.out.print("-");
        --n;
        new1(n);
        System.out.println();
        loop(n);
    }

}

static void loop(int n) {
    if (n > 0) {
        System.out.print("!!!-");
        loop(n - 1);
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-04-25
    • 1970-01-01
    • 1970-01-01
    • 2011-01-15
    • 1970-01-01
    • 2012-05-31
    • 2021-06-27
    • 1970-01-01
    相关资源
    最近更新 更多