2015-01-20 3 views
-1

내 문제는 간단하지만 나는 무엇을 위해 Google인지 알지 못합니다. 다른 내에서 생성 된 개체에 액세스

나는 어떻게 run.java 내에서 GLowestState에 액세스하기 위해 어떻게해야합니까, 기본적으로 그래서이

public class run { 
    //stuff 
    public static void main(String[] args) { 
     //stuff  
     Solver solver = new Solver(body,seeds); 
     solver.solve(); 
     LogTool.print("OUTPUT field of CLASS CREATED IN solver -- " + IDONTKNOWHOW,"notification"); 
    } 
} 
=========== 
public class Solver { 
    //stuff 
    public void solve() { 
     //stuff 
     GlobalState GLowestState = new GlobalState(this.Cur_state); 
    } 
} 

을하는 run.java이?

GLowestState가 싱글 톤으로 구현된다는 점에 차이가 있습니까?
아니겠습니까?
내 IDE에서 GLowestState.IDONTKNOWHOW에 대한 오류를 표시하므로 아무 것도 시도 할 수 없습니다. 더 많은 코드와

==============

업데이트 : GLowestState 만약

public class run { 
public static void main(String[] args) { 

     Voxel [][][] body = new Voxel[Config.xDIM][Config.yDIM][Config.zDIM]; 
     //stuff 

     Solver solver = new Solver(body,seeds);   

     LogTool.print("Initialized Solver Object!","notification"); 
     LogTool.print("Beginning Annealing...","notification"); 
     looper.solveSA(); 
     GlobalState GLS = looper.getGLowestState(); <--- NPE here 
     LogTool.print("GLC: " + looper.getGlobal_lowest_cost()+ " CURC: " + looper.getCur_cost(),"notification"); 
//  LogTool.print("GLS external: " + GLS,"notification"); 
     LogTool.print("SolveSA: Global Current Best Solution : " + looper.getGlobal_Lowest_state_string(),"notification"); 

========= 
public class Looper { 
    public static Voxel [][][] body; //Thobi hat das als ganz einfache Variable in seiner Loesermethode...nicht so OOP 
    public static Seed[] seeds = new Seed[Config.SAnumberOfSeeds]; 
    public double[] Cur_state = new double[Config.SAnumberOfSeeds]; 
    public double[] New_state = new double[Config.SAnumberOfSeeds]; // Do I even need this ? 
    public double[] Global_Lowest_state = new double[Config.SAnumberOfSeeds]; // Do I even need this ? 
    GlobalState GLowestState; 

    public Looper(Voxel [][][] body, Seed[] seeds) { 
     this.temperature = Config.StartTemp; 
     this.body = body; 
     this.seeds = seeds; 
       this.Cur_cost = Cur_cost; 
       this.New_cost = New_cost; 
       this.temperature = temperature; 
       this.Cur_state = Cur_state; 
       this.New_state = New_state; 
       this.Global_lowest_cost = Double.MAX_VALUE; 
       this.Global_Lowest_state = Global_Lowest_state; 
    } 

    public GlobalState getGLowestState() { 
     return GLowestState; 
    } 



     for (int ab = 0; ab < Config.NumberOfMetropolisResets; ab++) { 
      LogTool.print("==================== START CALC FOR OUTER ROUND " + ab + "=========================","notification"); 

      if (Config.SAverboselvl==1) { 
       LogTool.print("SolveSA: Cur_State Read before Metropolis : A)" + Cur_state[0] + " B) " + Cur_state[1] + " C) " + Cur_state[2],"notification"); 
       LogTool.print("Debug: GLS get 1: " + this.getGlobal_Lowest_state_string(),"notification"); 
      } 

      if (ab==0){ 
       this.initState(); 

       if (Config.SAverboselvl==1) { 
        LogTool.print("SolveSA: Cur_state after Initstate : A)" + Cur_state[0] + " B) " + Cur_state[1] + " C) " + Cur_state[2],"notification"); 
       } 
      } 

      setCur_cost(cost()); 

      /* [Newstate] with random dwelltimes */ 
      newState(); 
      if (Config.SAverboselvl==1) { 
       LogTool.print("SolveSA: New State before Metropolis: A)" + New_state[0] + " B) " + New_state[1] + " C) " + New_state[2],"notification"); 
      } 

      setNew_cost(cost()); 

      if (Config.SAverboselvl==1) { 
       LogTool.print("SolveSA: New Cost : " + New_cost,"notification"); 
      } 

      double random_double = RandGenerator.randDouble(0.01, 0.99); 

      /** 
       * MetropolisLoop 
       * @param Config.NumberOfMetropolisRounds 
      */ 

      for(int x=0;x<Config.NumberOfMetropolisRounds;x++) { 
    //   break; 
    //   LogTool.print("SolveSA Iteration " + x + " Curcost " + Cur_cost + " Newcost " + New_cost,"notification"); 
       if ((Cur_cost - New_cost)>0) { // ? die Kosten 

        if (Config.SAverboselvl>1) { 
         LogTool.print("Fall 1","notification"); 
        } 

        if (Config.SAdebug) {      
          LogTool.print("SolveSA: Metropolis NewCost : " + this.getNew_cost(),"notification"); 
          LogTool.print("SolveSA: Metropolis CurCost : " + this.getCur_cost(),"notification"); 
          LogTool.print("SolveSA Cost delta " + (Cur_cost - New_cost) + " ","notification"); 
        } 
          Cur_state = New_state; 
          Cur_cost = New_cost; 

        } else if (Math.exp(-(Cur_cost - New_cost)/temperature)> random_double) { 

         Cur_state = New_state; 
         Cur_cost = New_cost; 

         if (Config.SAdebug) { 
          LogTool.print("SolveSA: NewCost : " + this.getNew_cost(),"notification"); 
          LogTool.print("SolveSA: CurCost : " + this.getCur_cost(),"notification"); 
         } 

         if (Config.SAverboselvl>1) { 
          LogTool.print("Fall 2: Zufallsgenerierter Zustand traegt hoehere Kosten als vorhergehender Zustand. Iteration: " + x,"notification"); 
         } 
        } 

       temperature = temperature-1; 
       if (temperature==0) { 
        break; 
       } 

       random_double = RandGenerator.randDouble(0.01, 0.99); 
       newState(); 
       setNew_cost(cost()); 
      } 

      if (ab==9) { 
       double diff=0; 
      } 

//This is where the trouble happens - GlobalLoewst cost is set correctly and kept throughout the loops, GLowestState is always the last value of Cur_State (the most recent completed iteration. If smoothly running, that would be iteration 9 and inner iteration 99) @stackexchange 

      if (Cur_cost<Global_lowest_cost) { 
       this.setGlobal_lowest_cost(Cur_cost); 
       GlobalState GLowestState = new GlobalState(this.Cur_state); 
       LogTool.print("GLS DEDICATED OBJECT STATE OUTPUT -- " + GLowestState.getGlobal_Lowest_state_string(),"notification"); 
       this.setGlobal_Lowest_state(GLowestState.getDwelltimes()); 
       LogTool.print("READ FROM OBJECT OUTPUT -- " + this.getGlobal_Lowest_state_string(),"notification"); 
//    LogTool.print("DEBUG: CurCost direct : " + this.getCur_cost(),"notification");   
//    LogTool.print("Debug: Cur<global CurState get : " + this.getCur_state_string(),"notification"); 
//    LogTool.print("Debug: Cur<global GLS get : " + this.getGlobal_Lowest_state_string(),"notification"); 
//    this.setGlobal_Lowest_state(this.getCur_state(Cur_state)); 
//    LogTool.print("Debug: Cur<global GLS get after set : " + this.getGlobal_Lowest_state_string(),"notification");   
      } 
      LogTool.print("SolveSA: Iteration : " + ab,"notification"); 
      LogTool.print("SolveSA: Last Calculated New State/Possible state inner loop 99 : " + this.getNew_state_string(),"notification"); 
//   LogTool.print("SolveSA: Best Solution : " + this.getCur_state_string(),"notification"); 
      LogTool.print("SolveSA: GLS after: " + this.getGlobal_Lowest_state_string(),"notification"); 
      LogTool.print("SolveSA: NewCost : " + this.getNew_cost(),"notification"); 
      LogTool.print("SolveSA: CurCost : " + this.getCur_cost(),"notification");   
     } 
    } 

================= 

public final class GlobalState implements Comparable<Object>{ 
    private double[] dwelltimes; 
    private static GlobalState instance = null; 

    protected GlobalState(){ 
     // Exists only to defeat instantiation 
    } 

    public static GlobalState getInstance(){ 
     if (instance==null){ 
      instance = new GlobalState(); 
     } 
     return instance; 
    } 

    public GlobalState(double[] dwelltimes) { 
     this.dwelltimes = dwelltimes; 
    } 

    @Override 
    public int compareTo(Object o) { 
     throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. 
    } 

    public double[] getDwelltimes() { 
     return dwelltimes; 
    } 

    public String getGlobal_Lowest_state_string() { 
     String Global_Lowest_state_string = new String(); 
     for (int cc = 0; cc < Config.SAnumberOfSeeds; cc++) { 
      Global_Lowest_state_string = Global_Lowest_state_string.concat(" " + cc + ") " + dwelltimes[cc]); 
      } 
     return Global_Lowest_state_string; 
    } 

    public void setDwelltimes(double[] dwelltimes_x) { 
     this.dwelltimes = dwelltimes_x; 
    } 

} 
+0

를 호출하여 얻을 수 있습니다. –

+0

내 대답은 다니엘 아래 어떻게됩니까? 'public' 속성을 사용해야합니다. –

+0

ID는 더 많은 컨텍스트를 제공하고자합니다. 나는 원래 GlobalLowestState (간단히하기 위해 GLS) 필드를 가졌다. 어떤 조건이 충족되면 그 필드에 썼습니다. 이것은 solve() 메서드 내에서 검사되었습니다. 문제는 GLS가 전역 적으로 가장 중요한 상태 인 값 대신에 마지막으로 계산 된 Cur_State 값을 사용한다는 것입니다. 코드에서 오류가 발견되지 않았으므로 전역 변수 중 가장 낮은 값이 필드 대신 객체 GLS에 기록되었습니다. 기적적으로 GLS 개체에 올바른 값이 포함되어 있습니다. 그러나 그것은 get()을 사용하여 solver() 클래스 밖에서 접근 할 수 없었다. –

답변

0

는 당신이 정말로 그것을에 new를 호출 할 수있는 Singleton입니다 - - 잘 구현 된 Singleton이라고 가정합니다. 이 그럼 구현되면

당신은 다음과 같이 호출 :

GLowestState.getInstance(); 

또 다른 예 :

public class Solver { 
    private GlobalState GLowestState; 

    public void solve() { 
     GLowestState = new GlobalState(this.Cur_state); 
    } 

    public GlobalState getGLowestState() { 
     return GLowestState; 
    } 
} 
+0

내 코드가 nullpointer 예외로 실패합니다. 아래 보이는 방법은 성공적으로 실행되고 -> GLS 외부 : [email protected] (CTRL + K didnt work) : 그 안에있는 메소드 나 필드에 액세스하는 것은 실패합니다. 왜 ? solver.solve(); GlobalState GLSW = GlobalState.getInstance(); LogTool.print ("GLS external :"+ GlobalState.getInstance(), "notification"); –

0

이런 식으로 뭔가를 할 수 싱글 톤이되기 위해서는 private 생성자와 newInstance 메서드가 필요합니다. 오히려 local variable보다 변수 instance variable 만든뿐만 아니라, 게터

public class run { 
    //stuff 
    public static void main(String[] args) { 
     //stuff 
     Solver solver = Solver.getInstance().solve(body,seeds); 
     LogTool.print("OUTPUT field of CLASS CREATED IN solver -- " + solver.getGLowestState(),"notification"); 
    } 
} 
=========== 
public class Solver { 

    private GlobalState gLowestState; 
    private static Solver singeltonSolver; 

    private Solver() { 

    } 

    public synchronized static Solver getInstance(){ 
     if(singeltonSolver== null) 
      singeltonSolver = new Solver(); 
     return singeltonSolver; 
    } 

    public void solve(SOmeType body,SOmeType seeds) { 
     //stuff 
     GlobalState GLowestState = new GlobalState(this.Cur_state); 
    } 

    public GlobalState getGLowestState() { 
     return gLowestState; 
    } 
} 
+0

타입으로'public GlobalState getGLowestState()'를 의미한다고 생각합니다. – bcsb1001

+0

예. 고침, 고마워. –

0

당신이 원하는 경우 찾기 :

GLowestState.getInstance().foo(); 
+0

자바에서는 적어도 필드라고 부르며 속성은 아닙니다. – bcsb1001

0

당신은 당신의 클래스의 내부 개체에 대한 getter를 구현해야와 필드 gloweststate 액세스를 만듭니다. 코드의 경우, 예입니다 GLowestState 이제 클래스의 인스턴스가 아닌 방법 solve()에서 지역 변수에 속하는 방법

public class Solver { 
    // stuff 
    GlobalState GLowestState; 

    public void solve() { 
     // stuff 
     GLowestState = new GlobalState(this.Cur_state); 
    } 
    public GlobalState getGLowestState(){ 
     return GLowestState; 
    } 
} 

알 수 있습니다. 이제

Solver solver = new Solver(body,seeds); 
solver.solve(); 
GlobalState GS = solver.getGLowestState(); 

를 호출 할 수 있습니다 그리고 변수 GS는 Solver 개체의 특정 인스턴스에 대한 GlobalState 변수를 계속합니다.

+0

이것은 원래 구현하고 싶었던 것입니다. GlobalState 내부에서 필드의 두 배를 얻기 위해 getter를 사용했습니다. 그러나 GlobalState는 보이지 않습니다 ... –

+0

'GlobalState'를 보이게하고 싶다면 (당신이'Solver' 클래스 밖에서 사용하고자하는 별도의 클래스이기 때문에), 당신은 메서드를 사용하여'GlobalState' 객체의 세부 사항을 개별적으로 가져옵니다. 예를 들어,'GlobalState'에'int'와'String'을 가지고 있다면'getGlobalStateString()'메소드를 만들어'String' 메소드와'int' 메소드를 리턴 할 수 있습니다. 비록 내가 말했듯이, 그것은 다른 클래스 파일을 생성하고 그것이 현재 클래스 밖에서 사용될 것이라면 그것을 보이게하는 좋은 프로그래밍이다. –

+0

나는 이것을 구현했지만 아직 solver.getGLowestState를 탈출하려고 할 때 nullpointerexception을 얻는다. 나는 객체가 solveSA가 끝났을 때 파괴된다고 생각합니다. 아니면 idk ... –

0

내가해야 할 일은 GlobalState에 싱글 톤을 보유하는 것입니다.

public enum GlobalState { 
    INSTANCE; 

    public String getValue() { ... } 
} 

그러나 Solver은 전역 상태로 엉망이되지 않는 것이 좋습니다.

public class Solver { 
    final String field; 
    //stuff 
    public Solver(int body, int seeds) { 
     //solve stuff here 
     this.field = "value"; 
    } 
} 

public class Run { 
    //stuff 
    public static void main(String[] args) { 
     //stuff 
     Solver solver = new Solver(body,seeds); 
     LogTool.print("OUTPUT field of " + solver.field); 
    } 
} 
+0

enum을 사용하면 thek singleton을 구현하기에 좋지 않은 스타일이라는 것을 알았습니다. 왜 그것을 사용 했습니까? –

0

은 여러 가지 방법으로 accomplisched 수 :

1 GlowestState 경우 특히 IT와 객체를 돌려 사용을 반환 할 경우에만 다음 solve() 관련이있다.

public GlobalState solve() { 
    GlobalState globalState = new GlobalState(this.Cur_state); 
    return globalState; 
} 

지금 당신은 그것을 액세스 할 수 있습니다

Solver solver = new Solver(body,seeds); 
GlobalState globalState = solver.solve(); 

2가 GlowestState 인스턴스를 확인하고 공개.

public GlobalState glowestState; 
public void solve() { 
    GLowestState = new GlobalState(this.Cur_state); 
} 

그럼 당신은 GLowestState을 얻을 수있는 게터를 사용

3 solver.glowestState

를 호출하여 얻을 수 있습니다.

private GlobalState glowestState; 
public void solve() { 
    glowestState = new globalState(this.Cur_state); 
} 

public getGlowestState() { 
    return GLowestState; 
} 

지금 당신은 그것을 GLowestState` 현재 해결() 메소드로 제한됩니다`의 범위 getGlowestState()

관련 문제