I am having an issue where each class has multiple objects, it is a mess of objects being created of each class and I am having errors. The 4 class files are Main, Game, Updates Building, I will show the constructors of each class and hopefully someone can help me show how to create multiple objects of one class. There are variables in game that I need to access from update and building but when I try errors are returned. How do I access the variables in game from both update and building
Main:
public class Main
{
public static void main(String[] args)
{
Game newGame = new Game();
newGame.setupGame();
Game.isRunning=true;
newGame.gameLoop();
}
}
Game:
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;
}
Updates
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);
}
}
Building
import java.util.Scanner;
public class Building {
public Building(){
this.input = new Scanner(System.in);
}
private Scanner input;
}
I want the building class to be able to access the variables in main as well as the update class being able to access the variables in main.
解决方案
[EDITED]
Change in Updates class:
Building buildBuilding;
public Updates(Game newGame){
this.newGame = newGame;
this.input = new Scanner(System.in);
this.buildBuilding = new Building(newGame);
}
You have accidentally called an empty constructor, so
public Building(Game newGame){
this.input = new Scanner(System.in);
this.newGame = newGame;
}
was never called, and therefore input was NULL.