Can somebody help me fix this code? I keep getting a NPE.

edited February 2017 in Questions about Code

So I was following a tutorial about generating a Perlin Noise flow field in p5.js (The Coding Train Challenge #24) and I had a rough time converting from p5.js to Processing. I got stuck at implementing the particle system where I got a NullPointerException on line 44 (particles.update[0];). I haven't used vectors too much in the past. This is only supposed to display vector angles, then place a random particle on the screen.

Here's the main code:

int scl = 20;
int rows = 30;
int cols = 40;

float inc = 0.1;
float xoff;
float yoff;
float zoff = 0;

Particle[] particles = new Particle[100];

void setup() {
  size(800, 600);
  stroke(0);
}

void draw() {
  background(255);

  float r;

  yoff = 0;
  for(int y = 0; y < rows; y++) {
    xoff = 0;
    for(int x = 0; x < cols; x++) {
      r = noise(xoff, yoff, zoff) * TWO_PI;

      v = PVector.fromAngle(r);

      pushMatrix();
      translate(x*scl + scl, y*scl);
      rotate(v.heading());
      line(0,0,scl,0);
      popMatrix();

      xoff += inc;
    }
    yoff += inc;
    zoff += 0.01;
  }

  particles[0].update();
  particles[0].show();

}

Also, the Particle class:

class Particle {
  PVector pos = new PVector(random(width), random(height));
  PVector vel = new PVector(0,0);
  PVector acc = new PVector(0,0);

  void update() {
    vel.add(acc);
    pos.add(vel);
    acc.mult(0);
  }

  void aplyForce(PVector force) {
    acc.add(force);
  }

  void show() {
    stroke(0);
    point(pos.x, pos.y);
  }
}

Thanks in advance!

Tagged:

Answers

  • edited February 2017 Answer ✓

    Particle[] particles = new Particle[100]; merely instantiates the array container.
    We still need to instantiate each Particle and assign them to each array's indexed slot:
    for (int i = 0; i < particles.length; particles[i++] = new Particle());

  • Thanks a lot!

  • Answer ✓
    for (int i = 0; i < particles.length; i++)
        particles[i] = new Particle();
    
  • Answer ✓
    for (int i = 0; i < particles.length; i++) {
      particles[i] = new Particle();
    }
    
Sign In or Register to comment.