【问题标题】:Calculating fully connected mesh topology network count in Java用Java计算全连接网状拓扑网络数
【发布时间】:2013-04-22 23:27:56
【问题描述】:

问题是计算一个全连接网状拓扑网络的连接数。连接总数可以用公式 (n x (n-1)) / 2 计算。我们将递归地实现公共类ConnectionCount 方法,其他一切都交给我们。问题是它可以编译但不能正确运行。每个connectionCount 返回一个值 0。请帮忙,这是我目前所拥有的:

public class ConnectionCount {

    public int ConnectionCalc(int n) {
        if (n > 0) {
            return(n-1) + ConnectionCalc(n-1);
        }
        else {
            return 0;
        }
    }   

    public static int connectionCount(int n) {
        return 0;
    }

    public static void main(String [] args) {
        for (int i = 0; i < 20; i++) {
            System.out.println("connectionCount(" + i + ") returns " + connectionCount(i));

        }
    }
}

【问题讨论】:

  • 如果方法体只包含 return 0; ,你还能期待什么?请注意,ConnectionCalc 在任何地方都不会被调用。

标签: java recursion


【解决方案1】:

您正在调用始终返回 0 的方法 connectionCount,而不是调用 ConnectionCalc 方法。您还必须将 ConnectionCalc 声明为静态。

【讨论】:

  • 非常感谢,这是我的疏忽
猜你喜欢
  • 2018-03-16
  • 1970-01-01
  • 2022-07-05
  • 2014-10-14
  • 2011-03-31
  • 2011-05-08
  • 2010-10-26
  • 1970-01-01
  • 2012-07-13
相关资源
最近更新 更多