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

前端 未结 2 1134
离开以前
离开以前 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:19

    When you create an object array, you are creating an array of references, but you are not assigning the references. You must do this first before trying to use them. Think of it as being similar to creating an egg carton. You can't use any eggs until you first fill the carton with eggs. So for instance your blocks array, you first need to assign Rectangle objects to each item in the array before you can call methods on them. This is usually done in a for loop. e.g.,

    for(int i = 0; i < 24; i++){
        for(int e = 0; e < 24; e++){       
            blocks[i][e] = new Rectangle(....); //...             
            blocks[i][e].setBounds(e * 20, i * 20, 20, 20);
            blocks[i][e].setLocation(e*20, i*20);
    
    0 讨论(0)
  • 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);
    
    0 讨论(0)
提交回复
热议问题