Loading...
Logo
Processing Forum
I copied this code straight from a Processing book, and yet whenever I try to compile, I keep receiving a message stating: ArrayIndexOutOfBoundsException = 0. Anybody know why?

float[] sineWave = new float[width];

void setup() {
}

void draw() {

  for (int i=0; i < width; i++) {
    float r = map(i, 0, width, 0, TWO_PI);
    sineWave[i] = abs(sin(r));
  }

  for(int i=0; i<sineWave.length; i++) {
    //Set the stroke values to numbers read from the array
    stroke(sineWave[i] * 255);
    line(i, 0, i, height);
  }

}

Replies(3)

Hi,

you need to define width before to use it.
It could be look like that :

Copy code
  1. float[] sineWave;

  2. void setup() {
  3.   size(200,200);
  4.   sineWave = new float[width];
  5. }
+++
Sweet, thank you so much! One more question: why do I need to create the array in setup()? Why can't I create it outside of the setup() and draw() functions?
Because in Processing the 'width' variable is reserved for sketches screen width. And it gets actually defined only after the size() statement (in your example it becomes equal to 200). This is why you can use it only AFTER size(). You can try to initialize the array outside setup() (before it) if you use some custom defined variable.

Copy code
  1. int myvar = 200;
  2. float[] sineWave = new float[myvar];
Or just use a number (which is not recommended):

Copy code
  1. float[] sineWave = new float[200];