如果需要参数,如何实例化新的公共Java类?

时间:2012-08-23 01:12:28

标签: java constructor parameter-passing

我需要一个公开的数组(可以访问类中的其他方法),但是数组需要一个输入值“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方法访问渗滤。 救命啊!

2 个答案:

答案 0 :(得分:0)

不要在构造函数中包含类型声明。您正在创建一个掩盖该字段的局部变量。它应该是这样的:

public class PercolationStats {
    public double myarray[];
    public PercolationStats(int n, int y) {
        myarray = new double[t];
        for (i=0; i<t; i++) {
            Percolation percExperiment = 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);
    }
}

在创建新数组时使用变量作为长度肯定没问题。

答案 1 :(得分:0)

Tedd Hopp的回答纠正了代码中的错误。

我只想指出myarray不是全局变量。

  1. Java没有全局变量,
  2. 最接近的是static个变量,
  3. myarray也不是其中之一。它是一个实例变量,正如您已声明的那样。
  4. (实例变量是实现此目的的正确方法...... IMO)