我一直在爲這個問題尋找很多,我找不到解決方案。我試圖建立一個迷你遊戲,我有一個創建平臺的方法。我有一個每個平臺參數的類,我做了一個類的數組,所以我可以在同一時間有多個平臺。從類數組中調用方法會導致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