0

I am creating a small game in processing and I am trying to print a 2D array of square objects. I have this NullPointerException and I cannot seem to find anything like it on the web.

int edge = 10;
public int sizeOfRect = 50;
public int numberOfRects = 10;
Rectangle[][] player = new Rectangle[numberOfRects][numberOfRects];
public int k;
public int l;
public int kcount=0;
public int lcount=0;

void setup(){
    background(200);
    size(565, 565);
}
void draw(){
    for(k=edge; k<width-edge; k+=55){
        for(l=edge; l<height-edge; l+=55){
            player[kcount][lcount].display();
            lcount++;
        }
        lcount=0;
        kcount++;
    }
    kcount=0;
}

and the Rectangle Class

class Rectangle{
   int i;
   int j;
Rectangle(){
    i=k;//xcoor
    j=l;//ycoor
}

void display(){
    fill(0);
    rect(i,j,sizeOfRect,sizeOfRect);
    }

}

And finally the exception

Plain.pde:17:0:17:0: NullPointerException Finished. Could not run the sketch (Target VM failed to initialize). For more information, read revisions.txt and Help? Troubleshooting. Could not run the sketch.

Thank you in advance

Gabriele Mariotti
  • 320,139
  • 94
  • 887
  • 841
TedOiler
  • 3
  • 3
  • May because you must initialize the two-dimensional array in a `for` loop `player`, see https://stackoverflow.com/questions/12231453/syntax-for-creating-a-two-dimensional-array – Yu Jiaao Apr 03 '18 at 00:18

1 Answers1

0

You're creating a 2D array, but you're never filling that array with any objects. In other words, your 2D array is full of null values. That's why you're getting a NullPointerException.

You need to fill your array with values. Here's an example:

player[1][2] = new Rectangle();

You probably want to use a nested for loop to fill your array.

Kevin Workman
  • 41,537
  • 9
  • 68
  • 107