Loading...
Logo
Processing Forum
Hi,

i'm a noob to this forum but i've been using processing for a year or so. can anyone shed some light on why i'm getting an ArrayIndexOutOfBoundsException error in this script? (i've not found any solutions online so far)

I'm trying to create create a script where each blob is added to the array on each cycle of the draw loop (rather than created all at once using a for loop), but i seem to have a problem iterating through the array to display the blobs in each frame.

thanks for any help!

j

//script to add objects to an array (or arraylist) in sequence  depending on
//whether preceding item has given permission to create the next.

Blob[] blobList = new Blob[10];
int i = 0;    //counter for blobList

void setup(){
  size(200,200);
  frameRate(1);
}

void draw(){
  background(0);    //clear screen
 
  if(i < blobList.length){
    blobList[i] = new Blob();
  }
  i++;
 
  for(int j=0; j<i-1; j++){  //get an ArrayIndexOutOfBoundsException error here
     blobList[j].display();
  }
}

class Blob{
  PVector loc;
  boolean canGo;
  int count;
 
  Blob(){
    loc = new PVector(random(width),random(height));
  }
 
  void display(){
    fill(125);
    ellipseMode(CENTER);
    ellipse(loc.x,loc.y,10,10);
  }
}

Replies(4)

If you just want to have 9 Blobs, then the i++ is the one giving you the problem. Put it inside if (i < blobList.length) {} and it should work fine. (Put it after blobList[i] = new Blob();)

The reason you get an error is because you are using a normal array which has fixed length of 10 slots. However, you keep increasing the maximum index (using i++) even after i is bigger than your array length. So when you were trying to display the blobList and when i is bigger than 11, it gives you an error because blobList only has an array length of 10.
great, thanks for that! (i feel a bit stupid now)

i wanted to avoid all the blobs being created in one frame, but took the i++ too far out of the loop.

j
Haha yes, that happens :)
Something to try when you get this message is to println the values that are changing, sometimes before and after the change (largely irrelevant in this case):
before if(i< ..)
println("before " + i);
then after i++;
println("after " + i);
 
veeableful is right, i++ is causing the problem. As it is, there's nothing to stop it getting bigger than the length of your array. You could add a trap:
if(i < blobList.length) i++;