【问题标题】:Java program logic needs to be explainedJava程序逻辑需要解释
【发布时间】:2015-04-04 23:40:43
【问题描述】:

我的书有一个类似this的程序。

public class Partition { 

public static void partition(int n) {
    partition(n, n, "");
}
public static void partition(int n, int max, String prefix) {
    if (n == 0) {
        StdOut.println(prefix);
        return;
    }

    for (int i = Math.min(max, n); i >= 1; i--) {
        partition(n-i, i, prefix + " " + i);
    }
}


public static void main(String[] args) { 
    int N = Integer.parseInt(args[0]);
    partition(N);
}

}

是否有另一种以不同方式编写 for 循环的方式,对我来说并不那么复杂?谢谢!

【问题讨论】:

  • 您认为方法调用Math.min 有什么作用?你读过javadoc吗?
  • 你让自己被未知事物吓倒。但是您“知道”此方法可能会做什么,如果不知道,您肯定会发现,将单个调用与其执行的代码交换不会使这更容易理解,我不认为。
  • 看看the docs。

标签: java loops logic


【解决方案1】:

在尝试理解递归方法/函数时,我发现添加一些明智的调试代码会很有帮助,这些代码可以告诉您每一步发生了什么。为了增加视觉吸引力,我添加了一个 debugIndent,它可以直观地告诉我我所处的级别。

StdOut(debugIndent + "n = " + n + ", max = " + max + ", prefix = \"" prefix + "\""); 

把它放在你的第二个分区的开头,像这样:

Public class Partition { 

    public static void partition(int n) {
        partition("", n, n, "");
    }
    public static void partition(String debugIndent, int n, int max, String prefix) {
        StdOut(debugIndent + "n = " + n + ", max = " + max + ", prefix = \"" prefix + "\""); // TODO remove debugging code

        if (n == 0) {
            StdOut.println(prefix);
            return;
        }

        for (int i = Math.min(max, n); i >= 1; i--) {
            partition(debugIndent + "  ", n-i, i, prefix + " " + i);
        }
    }


    public static void main(String[] args) { 
        int N = Integer.parseInt(args[0]);
        partition(N);
    }
}

运行它并查看它显示的内容。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-02
    • 1970-01-01
    • 2012-04-22
    • 2015-09-15
    • 2013-08-04
    • 2022-06-15
    • 1970-01-01
    相关资源
    最近更新 更多