I'm getting a NullPointerException

Can someone help me fix this problem. when I run this code I get a NullPointerException at rockets[i].update(), and even if I comment that out I get the same error but on rockets[i].display() and I don’t know why I have tried making it a single object and I have tried putting only one item in the array, but I still can figure it out.

Thanks in advance

Rockets[] rockets;

void setup() {
  size(1200, 800);
  rockets = new Rockets[1];
}

void draw() {
  background(0);
  for (int i=0; i < rockets.length; i++) {
    rockets[i].update();
    rockets[i].display();
  }
}


public class Rockets
{
  PVector pos;
  PVector vel;
  PVector acc;

  void rockets() {
    this.pos = new PVector(width/2, height);
    this.vel = new PVector(0, -1);
    this.acc = new PVector();
  }

  void applyForce(PVector Force) {
    this.acc.add(Force);
  }

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

  void display() {
    stroke(255);
    strokeWeight(2);
    fill(255, 200);
    rect(this.pos.x, this.pos.y, 50, 10);
  }
}

Hey,

This is because you didn’t initialize your array of rockets, you have to say :

rockets[0] = new Rockets();

And this is the right syntax (look at https://processing.org/reference/class.html) for a class :

public class Rockets
{
  PVector pos;
  PVector vel;
  PVector acc;

  Rockets() {
    pos = new PVector(width/2, height);
    vel = new PVector(0, -1);
    acc = new PVector();
  }

  void applyForce(PVector Force) {
    acc.add(Force);
  }

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

  void display() {
    stroke(255);
    strokeWeight(2);
    fill(255, 200);
    rect(pos.x, pos.y, 50, 10);
  }
}
2 Likes

Hey,

I’m getting a nullpointerexception at rockets[0] = new Rockets();

I changed my code to this

Rockets[] rockets;

public void setup() {
  size(1200, 800);
  rockets[0] = new Rockets();
}

void draw() {
  background(0);
  for (int i=0; i < rockets.length; i++) {
    rockets[i].update();
    rockets[i].display();
  }
}


public class Rockets
{
  PVector pos;
  PVector vel;
  PVector acc;

  Rockets() {
    pos = new PVector(width/2, height);
    vel = new PVector(0, -1);
    acc = new PVector(0, -1);
  }

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

  void display() {
    stroke(255);
    strokeWeight(2);
    fill(255, 200);
    rect(this.pos.x, this.pos.y, 50, 10);
  }
}

Sketches w/ array of objects: :slightly_smiling_face:

  1. sketchpad
  2. sketchpad
  3. sketchpad
  4. sketchpad
  5. sketchpad
  6. sketchpad