我一直在为这个问题寻找很多,我找不到解决方案。我试图建立一个迷你游戏,我有一个创建平台的方法。我有一个每个平台参数的类,我做了一个类的数组,所以我可以在同一时间有多个平台。从类数组中调用方法会导致NullPointerException
问题:当我尝试通过发送参数来调用构建平台的方法时,它给了我一个NullPointerException
。该方法之前工作,但一切都是静态的,所以我不能拥有该类的多个实例,现在我从平台类中删除了静态字段,并且每次调用该方法时都会给我提供NullPointerException
。
我复制了给我的错误代码的一部分,错误进入方式如下:
public static void main(String[] args) {
Game ex = new Game();
new Thread(ex).start();
}
在游戏类:
public Load_Stage load = new Load_Stage();
public Game() {
-other variables initializatin-
Initialize_Items();
load.Stage_1(); // <--- problem this way
在Load_Stage类:
public class Load_Stage {
public Platforms plat = new Platforms();
public void Stage_1(){
Stage_Builder.Build_Platform(200, 500, 300, plat.platform1);
Stage_Builder.Build_Platform(100, 200, 100, plat.platform1);
}
}
而在Stage_Builder类中:
public class Stage_Builder {
public static final int max_platforms = 10;
public static Platform_1[] p1 = new Platform_1[max_platforms];
public static boolean[] platform_on = new boolean[max_platforms];
public Stage_Builder() {
for (int c = 0; c < platform_on.length; c++) {
platform_on[c] = false;
}
}
public static void Build_Platform(int x, int y, int width, ImageIcon[] type) { // BUILDS A PLATFORM
for (int b = 0; b < max_platforms; b++) {
if (platform_on[b] == false) {
p1[b].Construct(x, y, width, type); // <-- NullPointerException here
platform_on[b] = true;
break;
}
}
}
}
预先感谢。
编辑:这里是Platform_1类(对不起,忘掉它):
public class Platform_1 {
private int platform_begin_width = 30;
private int platform_middle_width = 20;
public int blocks_number = 0;
public ImageIcon[] platform_floors = new ImageIcon[500];
private int current_width = 0;
public int [] platform_x = new int [500];
public int platform_y = 0;
public int platform_width = 0;
public void Construct(int x, int y, int width, ImageIcon [] type) {
platform_width = width;
platform_y = y;
for (int c = 0; current_width <= platform_width; c++) {
if (c == 0) {
platform_x[c] = x;
platform_floors[c] = type[0];
current_width += platform_begin_width;
} else if ((current_width + platform_middle_width) > platform_width) {
platform_floors[c] = type[2];
blocks_number = c + 1;
platform_x[c] = current_width + x;
current_width += platform_middle_width;
} else {
platform_floors[c] = type[1];
platform_x[c] = current_width + x;
current_width += platform_middle_width;
}
}
}
}
而平台类:
public class Platforms {
public ImageIcon[] platform1 = {new ImageIcon("Resources/Sprites/Stage_Objects/Platform1/begin.png"),
new ImageIcon("Resources/Sprites/Stage_Objects/Platform1/middle.png"),
new ImageIcon("Resources/Sprites/Stage_Objects/Platform1/end.png")};
}
对不起忘记p1数组代码。我编辑了这篇文章。我会检查你的解决方案,看看它是否工作,谢谢:) –
好吧,我如何初始化P1,指向Platform_1的非null实例?我知道你的意思,我只是不知道如何实施解决方案 –
查看示例代码 – duffymo