Question

I finding it hard to understand Array Objects. In this case I don't know why 'wal[i].walk();' is considered a Null Pointer Exception.

walker[] wal;
int num= 70;
void setup() {
  size(800, 600);
  wal = new walker[num];
  background(255);
}

void draw() {

  for (int i = 0; i < num; i++) {
    wal[i].walk();
    wal[i].display();
  }
}



class walker {
  int x, y;
  float r, g, b;

  walker(float red, float green, float blue) {
    x = width/2;
    y = height/2; 
    r = red;
    g= green;
    b= blue;
  }

  void walk() {
    int choice = int(random(4));

    if (choice == 0) {
      x++;
    } 
    else if (choice == 1) {
      x--;
    }
    else if (choice == 2) {
      y++;
    }
    else {
      y--;
    }

    x = constrain(x, 0, width-1);
    y = constrain(y, 0, height-1);
  }



  void display() {

    stroke(r, g, b);
    point(x, y);
  }
}

Then I add some filler text as I'm being told I have posted too much code for the amount of text that I have, even though the text above the code sufficiently explains the problem without becoming patronising or going off topic.

Was it helpful?

Solution

Well... As far as I can understand you want an array of "num" walkers. You are properly initializing your array here:

wal = new walker[num];

You are stating that in the object wal there will be a "new" object of type "walker array" and holds "num" number of objects (new walker[num]);

Think of an array as an object pointing to other objects. You need to initialize both the array itself and the objects it points to. That means of course, going over each object and specifying what that object is. You can do this right after your array initialization thus add the lines:

for (int i = 0; i < num; i++) {
  wal[i] = new walker(255,167,15);
}

Here, we are iterating over the array, picking each object (wal[i]) and saying that in there should be a new walker with the values 255 167 and 15 (new walker(255,167,15))

If you don't do this, when the program tries to access an object in the array (wal[i]) it finds nothing(null) therefore it throws an nice nullPointerException in your face!

For fun and for profit you can also try this instead:

for (int i = 0; i < num; i++) {
  wal[i] = new walker(random(255),random(255),random(255));
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top