2012-08-23 56 views
-2

我需要一個數組是公有的(可以被類中的其他方法訪問),但是數組需要一個輸入值「T」來創建它。如何實例化需要用戶輸入的「全局」變量?如何在需要參數的情況下實例化新的公共Java類?

我的代碼如下:

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** 
    } 
} 

在第二個例子,在我看來,我需要有一流的WQF所做的新實例在Percolation的構造函數中,以接受參數N.但是,WQF不可用於Main方法的滲濾。 幫助!

+1

。匆匆一瞥,人們會認爲你正在用'T'等語言泛泛而談。 –

+0

你的第二個例子非常混亂。爲什麼你有兩個主要方法? –

+0

'Percolation percExperiment as new Percolation(N)' - 這甚至是Java嗎? –

回答

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); 
    } 
} 

創建新數組時使用變量作爲長度肯定沒有問題。

0

泰德霍普的答案糾正了你的代碼中的錯誤。

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

  1. Java沒有全局變量,
  2. 它最接近的是static變量,
  3. myarray是不是其中的一個無論是。這是一個實例變量,因爲您已聲明它。

(和實例變量來實現這個正確的方式... IMO)我建議你使用正確的命名約定變量

相關問題