2014-12-28 60 views
0

我正在製作一個2D側滾動遊戲,我卡住了。我正在爲將會產生越來越多的對象和玩家必須避免的對象編寫類。但令人遺憾的是,我得到了一個N​​ullpointerexception,我無法弄清楚爲什麼。在我清理了主代碼並將其轉換爲一個類之前,整個事情都奏效了。我想我正確地初始化數組,沒有變量沒有定義。過去幾個月我一直在使用處理,所以我可能會監督一些事情。數組中處理中的空指針異常。試了一切

非常感謝您的幫助

public class Blockfield { 
    private int Blockcount; 
    private PImage Blockpic; 
    private Block block[]; 

    //Constructor 
    public Blockfield (int Blockcount) { 
    this.Blockcount = Blockcount; 
    //new array 
    block = new Block [Blockcount]; 
    for (int i=0; i < Blockcount; i++) { 
     block[i] = new Block(width+Blockpic.width, random (height)); 
    } 
    } 


    //Draw method for this class 
    public void draw() { 
    for (int i =frameCount/100; i >0; i--) { 
     image (Blockpic, block[i].x, block[i].y); 
     //moves blocks right to left 
     block[i].x -=7 ; 
     //spawns block when they leave the screen 
     if (block[i].x < 0) { 
     block[i] = new Block(width+Blockpic.width, random (height)); 
     } 
    } 
    } 
} 

class Block { 
float x, y; 

Block (float x, float y) { 
this.x= x; 
this.y= y; 
} 
} 

主營:

Blockfield blockfield; 
PImage Blockpic; 



void setup() { 
    size (1291, 900); 
    blockfield = new Blockfield(100); 

    Blockpic = loadImage("block2.png"); 
} 


void draw() { 
    background (10); 

} 
+3

您是否使用了該編程語言的名稱? –

+1

您的NullPointer在哪裏發生? – tddmonkey

+1

在'Blockpic'已經分配之前,您正在'Blockfield'構造函數中訪問'Blockpic.width'。 –

回答

0

的問題是,我是想在你的Blockfield構造訪問Blockpic.widthBlockpic已經分配了。解決方案是在類的構造函數中加載Image。

工作代碼:

public class Blockfield { 
    private int Blockcount; 
    private PImage Blockpic; 
    private Block block[]; 

    //Constructor 
    public Blockfield (int Blockcount) { 
    this.Blockcount = Blockcount; 
    Blockpic = loadImage("block2.png"); 
    //new array 
    block = new Block [Blockcount]; 
    for (int i=0; i < Blockcount; i++) { 
     block[i] = new Block(width+Blockpic.width, random (height)); 
    } 
    } 


    //Draw method for this class 
    public void draw() { 
    for (int i =frameCount/100; i >0; i--) { 
     image (Blockpic, block[i].x, block[i].y); 
     //moves blocks right to left 
     block[i].x -=7 ; 
     //spawns block when they leave the screen 
     if (block[i].x < 0) { 
     block[i] = new Block(width+Blockpic.width, random (height)); 
     } 
    } 
    } 
} 

class Block { 
float x, y; 

Block (float x, float y) { 
this.x= x; 
this.y= y; 
} 
} 

感謝大家的幫助!