2016-11-13 42 views
0

我有一個問題,其中每個類有多個對象,它是每個類創建的對象的混亂,我有錯誤。 4類文件是Main,Game,Updates Building,我將展示每個類的構造函數,並希望有人可以幫助我演示如何創建一個類的多個對象。我需要從更新和構建中訪問遊戲中的變量,但是當我嘗試返回錯誤時。如何訪問這些變量在遊戲中來自更新及建築Java:擁有一個類的多個對象

主營:

public class Main 
{ 

    public static void main(String[] args) 
    { 
     Game newGame = new Game(); 

     newGame.setupGame(); 
     Game.isRunning=true; 
     newGame.gameLoop(); 

    } 

} 

遊戲:

import java.util.Scanner; 

public class Game { 

    private Scanner input; 
    private Updates getUpdates; 

    public Game(){ 
     this.input = new Scanner(System.in); 
     this.getUpdates = new Updates(this); 
    } 
int happyness; 
double money; 
int population = 1000000; 

} 

更新

import java.util.Scanner; 

public class Updates { 

    private Scanner input; 

    private Game newGame; 

    Building buildBuilding = new Building(); 

    public Updates(Game newGame){ 
     this.newGame = newGame; 
     this.input = new Scanner(System.in); 
    } 
} 

大廈

import java.util.Scanner; 

public class Building { 

    public Building(){ 

     this.input = new Scanner(System.in); 
    } 

    private Scanner input; 
} 

我想讓building類能夠訪問main中的變量以及能夠訪問main中的變量的update類。

+0

Building類的哪些變量?輸入? – developer

+3

我已經讀了3次,不明白你想要什麼。你有什麼錯誤?你想達到什麼目的? –

+0

歡迎來到堆棧溢出!請查看我們的[SO問題清單](http://meta.stackoverflow.com/questions/260648/stack-overflow-question-checklist)來幫助你提出一個好問題,從而得到一個很好的答案。 –

回答

0

將帖子

變化更新類:

Building buildBuilding; 

public Updates(Game newGame){ 
    this.newGame = newGame; 
    this.input = new Scanner(System.in); 
    this.buildBuilding = new Building(newGame); 
} 

你不小心叫一個空的構造,所以

public Building(Game newGame){ 

     this.input = new Scanner(System.in); 
     this.newGame = newGame; 
    } 

從未被調用,因此input是NULL。

+0

不,我知道如何獲取變量,但是當我嘗試從兩個不同的類同時完成[訪問2個不同類的遊戲中的變量]時,我得到一個錯誤 –

+0

您能否提供一個可運行的代碼,發生?我無法用這個小樣本來引發錯誤。 –

+0

虐待在這裏爲每個類提供粘貼bin代碼:http://pastebin.com/KVqYtiMB –

相關問題