processing - NPE in simple sketch -


i finding hard understand array objects. in case don't know why 'wal[i].walk();' considered null pointer exception.

walker[] wal; int num= 70; void setup() {   size(800, 600);   wal = new walker[num];   background(255); }  void draw() {    (int = 0; < 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 add filler text i'm being told have posted code amount of text have, though text above code sufficiently explains problem without becoming patronising or going off topic.

well... far can understand want array of "num" walkers. initializing array here:

wal = new walker[num]; 

you stating in object wal there "new" object of type "walker array" , holds "num" number of objects (new walker[num]);

think of array object pointing other objects. need initialize both array , objects points to. means of course, going on each object , specifying object is. can right after array initialization add lines:

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

here, iterating on array, picking each object (wal[i]) , saying in there should new walker values 255 167 , 15 (new walker(255,167,15))

if don't this, when program tries access an object in array (wal[i]) finds nothing(null) therefore throws nice nullpointerexception in face!

for fun , profit can try instead:

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

Comments

Popular posts from this blog

html - How to style widget with post count different than without post count -

How to remove text and logo OR add Overflow on Android ActionBar using AppCompat on API 8? -

javascript - storing input from prompt in array and displaying the array -