【发布时间】:2012-08-23 01:12:28
【问题描述】:
我需要一个公开的数组(类中的其他方法可以访问),但该数组需要一个输入值“T”来创建它。如何实例化需要用户输入的“全局”变量?
我的代码如下:
public class PercolationStats {
**private double myarray[];**
public PercolationStats(int N, int T) {
**double myarray = new double[T];**
for (i=0;i<T;i++) {
Percolation percExperiment as new Percolation(N);
//do more stuff, make calls to percExperiment.publicmethods
myarray[i] = percExperiment.returnvalue;
}
}
public static void main(String[] args) {
int N = StdIn.readInt();
int T = StdIn.readInt();
PercolationStats percstats = new PercolationStats(N, T);
//do more stuff, including finding mean and stddev of myarray[]
StdOut.println(output);
}
另一个伪代码示例:
class PercolationStats {
Constructor(N, T) {
new Percolation(N) //x"T" times
}
Main {
new PercolationStats(N, T) //call constructor
}
}
class Percolation {
Constructor(N) {
**new WQF(N)** //another class that creates an array with size dependent on N
}
Main {
**make calls to WQF.publicmethods**
}
}
在第二个示例中,在我看来,我需要在 Percolation 的构造函数中创建类 WQF 的新实例才能接受参数 N。但是,WQF 的 Main 方法将无法访问渗滤。 救命!
【问题讨论】:
-
我建议对变量使用正确的命名约定。乍一看,人们会认为你在谈论泛型,而
T等会被到处乱扔。 -
您的第二个示例非常令人困惑。为什么有两种主要方法?
-
Percolation percExperiment as new Percolation(N)- 这甚至是 Java 吗?
标签: java constructor parameter-passing