null pointer exception when initializing a 2D object array [Java]

前端 未结 2 1133
离开以前
离开以前 2021-01-23 23:55

I\'m trying to make a 2D tile game and when making the arrays holding the tiles I get a NullPointerException, here is some of the code. Sorry if this is poorly formatted, first

2条回答
  •  梦谈多话
    2021-01-24 00:39

    You need to know that Java is not like C.

    When you do this:

    Rectangle[][] blocks = new Rectangle[25][25];
    

    All the references in the blocks 2D array are null until you call new and give them a reference.

    So you'll have to do this:

    for(int i = 0; i < 24; i++){
        for(int e = 0; e < 24; e++){             
            blocks[i][e] = new Rectangle(); // I don't know what arguments it takes.       
            blocks[i][e].setBounds(e * 20, i * 20, 20, 20);
            blocks[i][e].setLocation(e*20, i*20);
    

提交回复
热议问题