Array of Objects Returns Null

I've just started to use arrays of objects in processing. I introduce the array with

Mass[] masses = new Mass[n];

However this returns an array of nulls. Here is my code:

float dt = 1;
int n = 10;
Mass[] masses = new Mass[n];

void setup(){
  size(1000, 1000);
  background(0);
  for (Mass mass : masses) {
    mass.initialize();//null point exception here
    println("done");
  }
  frameRate(1000);
}

void draw(){
  for (Mass mass : masses) {
    mass.update();
    mass.dr();
  }
  println(frameRate); 
}

My class is defined here:

class Mass {
  float x=0; //xpos
  float y=0; //ypos
  float vx=0; //xvel
  float vy=0; //yvel
  float ax=0; //xacc
  float ay=0; //yacc
  
  void initialize(){
    x = random(0, width);
    y = random(0, height);
    vx = random(0, 1);
    vy = random(0, 1);
  }
  
  void update(){
    float r = sqrt(sq(x-width/2)+sq(y-height/2));
    float xcomp = ((width/2)-x)/r;
    float ycomp = ((height/2)-y)/r;
    float str = 200;
    ax = str*xcomp/sq(r);
    ay = str*ycomp/sq(r);
    x = x + vx*dt + 0.5*ax*sq(dt);
    y = y + vy*dt + 0.5*ay*sq(dt);
    vx = vx + ax*dt;
    vy = vy + ay*dt;
  }
  
  void dr(){
    stroke(255);
    point(x, y);
  }
}`

If you could help me out, I would be so happy.

Upvotes: 1

Views: 123

Answers (1)

Rabbid76
Rabbid76

Reputation: 210877

You have create an array, but not the objects in the array. Construct new objects:

void setup(){
    // [...]

    for (int i = 0; i < masses.lenght; i++) {
        masses[i] = new Mass();
        mass.initialize();
    }

    // [...]
}

However, I recommend removing the initialize method but implementing a constructor:
(see Processing - [class])

void setup(){
    // [...]

    for (int i = 0; i < masses.lenght; i++) {
        masses[i] = new Mass();
    }

    // [...]
}
class Mass {
    // [...]

    // void initialize(){    <--- remove "initialize" method 
  
    Mass(){               // <--- add constructor
       
        x = random(0, width);
        y = random(0, height);
        vx = random(0, 1);
        vy = random(0, 1);
    }

    // [...]
}

Upvotes: 2

Related Questions