Why is there an array out of bounds here?

mover[] james;
attractor ben;
boolean start = false;
float[][][] orbits = new float[5][20000][1];
int njames = 5;
int orbitcount = 0;
float fconstant = 0.005;
void setup() {
  size(800, 800);

james = new mover[njames];
ben = new attractor();
for (int i = 0; i < njames; i ++) {
  
  james[i] = new mover();
}
}

void draw() {
  if (frameCount % 50 == 0) {
     start = true;
    orbitcount ++;
  }
  background(0);

  beginShape();
  noFill();
  stroke(255);
  for (int i = 0; i < njames; i ++) {
    if (mousePressed) {
    PVector wind = new PVector(0.1, -0.1);
    james[i].applyforce(wind);
    
  }
  PVector vclone = james[i].velocity.get();
  PVector friction = (vclone.normalize().mult(-1 * fconstant));
  james[i].applyforce(friction);
  PVector force = ben.attract(james[i]);
  james[i].applyforce(force);
  vertex(james[i].location.x, james[i].location.y);
  james[i].move();

  james[i].show();
  if(start) {
    orbits[i][orbitcount][0] = james[i].location.x;
    orbits[i][orbitcount][1] = james[i].location.y;
  
  }
  }
  
  endShape(CLOSE);
  
 for (int i = 1; i < njames; i ++) {
    beginShape();
    for (int n = 1; n < 20000; n ++) {
      if (!(orbits[i][n][0] == 0 && orbits[i][n][1] == 0)) {
        vertex(orbits[i][n][0], orbits[i][n][1]);
        print(orbits[i][n][0], orbits[i][n][1]);
      }
    }
    endShape();
} 

}
1 Like

Could you edit your post and reformat your code using the </> button?

At which line do you get the error?

thanks for the reply, its the line


if (!(orbits[i][n][0] == 0 && orbits[i][n][1] == 0)) {

In this line you only declare one array element for the third dimension of this array. Remember, when you use float[] f = new float[3] you get an array with 3 elements with indices 0, 1 and 2. So if you make an array like this: new float[5][20000][1]; the third dimension only has one element with index 0.

1 Like

ah ok i didnt know that, im used to vb where that doesnt happen, thanks