我制作的游戏需要更新类来访问游戏类和主类来访问这两者。我遇到的问题是我需要更新类来获得游戏类的更新对象,但每当我尝试从Update类访问游戏类时我都会收到错误[newGame.test();]错误/ p>
ERROR: Exception in thread "main" java.lang.NullPointerException
at Updates.updateStats(Updates.java:17)
at Game.gameLoop(Game.java:24)
at Main.main(Main.java:14)
import java.util.Scanner;
public class Main
{
static Scanner input = new Scanner(System.in);
public static void main(String[] args)
{
Game newGame = new Game();
//Updates getUpdates = new Updates();
newGame.setupGame();
Game.isRunning=true;
newGame.gameLoop();
}
}
import java.util.Scanner;
public class Game {
static Scanner input = new Scanner(System.in);
Updates getUpdates = new Updates();
public Game(){
}
String goverment;
int happyness;
double money;
int population = 1000000;
public static boolean isRunning;
private int turn = 0;
public void gameLoop(){
while (isRunning){
getUpdates.updateStats();
System.out.println("Turn: "+turn);
input.nextLine();
turn++;
}
}
public void setupGame()
{
System.out.println("Goverment: 1=Democracy 2=monarchy 3=dictatorship");
goverment = input.nextLine();
while (!goverment.equals("1")||!goverment.equals("2")||!goverment.equals("3")){
if (goverment.equals("1")){
happyness = 75;
money = 250000.0;
break;
}
else if (goverment.equals("2")){
happyness = 50;
money = 500000.0;
break;
}
else if (goverment.equals("3")){
happyness = 25;
money = 750000.0;
break;
}
else{
System.out.println("ENTER A VALID VALUE");
goverment = input.nextLine();
}
}
System.out.println("1");
}
public int getHappyness(){
return happyness;
}
public void test(){
System.out.println("MY NAME IS BOB");
}
}
import java.util.Scanner;
public class Updates {
static Scanner input = new Scanner(System.in);
public Updates(){
}
public Updates(Game newGame){
this.newGame = newGame;
}
Game newGame;
public void updateStats(){
newGame.test();
}
}
答案 0 :(得分:0)
对不起,如果这不是很有帮助,但这是我第一次在这里回答问题。
我将您的代码放入测试项目中以查看问题所在,并且您似乎遇到了一些错误。
我将从Main类开始,因为它有最小的问题。
您不需要在此处声明扫描仪对象,因为它从未使用过。您只是将内存分配给空对象。
现在,进入Updates类。
同样,无需在此声明扫描仪。
使用对象" newGame"你需要确保你正在使用构造函数:
public Updates(Game newGame){
this.newGame = newGame;
}
而不是:
public Updates(){
}
因为后者不会为你设置Game对象,所以当你访问它时,你会得到一个nullpointer。
最后,游戏类:
我将Scanner和Updates对象都设为私有,因为它们从未在课堂外使用过。如果是,请使用getters and setters。
在你的游戏构造函数中,你可以实际创建getUpdates和输入对象,如下所示:
public Game() {
this.input = new Scanner(System.in);
this.getUpdates = new Updates(this);
}
这样,无论何时初始化游戏,您都可以随时使用它们。如你所见,我把
new Updates(this)
使用我之前提到的Updates构造函数。这应该最终解决您的问题。
作为参考,以下是我使用/编辑过的文件,它在我的最后工作: