2012-08-23 3 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는 퍼콜 레이션의 기본 메소드에 액세스 할 수 없습니다. Help!

+1

(그리고 인스턴스 변수는이를 구현하는 올바른 방법 ... IMO)입니다. 한눈에 사람들은'T' 등으로 제네릭을 쓰고 있다고 생각할 것입니다. –

+0

두 번째 예는 매우 혼란 스럽습니다. 왜 두 가지 주요 방법이 있습니까? –

+0

'PercExperiment as new Percolation (N)'-이게 자바인가? –

답변

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

Tedd Hopp의 답변으로 코드의 버그가 수정되었습니다.

myarray은 글로벌 변수가 아닙니다.

  1. 자바 글로벌 변수가없는,
  2. 가 가지고있는 가장 가까운 static 변수이며,
  3. myarray 역시 그 중 하나가 아닙니다. 사용자가 선언 한대로 인스턴스입니다.

내가 변수에 대한 적절한 이름 지정 규칙을 사용하는 것이 좋습니다 것

관련 문제