Sim
Sim

Reputation: 231

ArrayIndexOutOfBounds 8 exception on processing

I'm getting an error of ArrayIndexOutOfBounds 8 I'm not sure why- my images start from 0. The line processing seems to be highlighting is image(images[ic], gridX, gridY, stepX, stepY); Any help to resolve this will be really helpful. Thanks in advance!

import java.util.Calendar;
PImage[] images = new PImage[8];
int ic;
PImage img;

void setup(){
  size(500, 500);

  for ( int i = 0; i< images.length; i++ )
{
images[i] = loadImage( i + ".png" );   // make sure images "0.jpg" to "11.jpg" exist
}  
}

void draw(){
  ic= 0;
  float tileCountX =10;
  float tileCountY = 10;
  float stepX = width/tileCountX;
  float stepY = height/tileCountY;
  for (float gridY = 0; gridY < height; gridY += stepY){
    for (float gridX = 0; gridX < width; gridX += stepX){
           image(images[ic], gridX, gridY, stepX, stepY);
           ic++;  
  }
  }
}

void keyReleased(){
  if (key=='s' || key=='S') saveFrame(timestamp()+"_##.png");
}

// timestamp
String timestamp() {
  Calendar now = Calendar.getInstance();
  return String.format("%1$ty%1$tm%1$td_%1$tH%1$tM%1$tS", now);
}

Upvotes: 0

Views: 102

Answers (1)

Kevin Workman
Kevin Workman

Reputation: 42174

Look at this block of code:

  ic= 0;
  float tileCountX =10;
  float tileCountY = 10;
  float stepX = width/tileCountX;
  float stepY = height/tileCountY;
  for (float gridY = 0; gridY < height; gridY += stepY){
    for (float gridX = 0; gridX < width; gridX += stepX){
           image(images[ic], gridX, gridY, stepX, stepY);
           ic++;  
     }
   }

Your width and height are 500, so that inner loop is going to execute 500 times. You're incrementing ic each time.

You're using that ic variable to index into your array- but your array only has 8 indexes, not 500. That's what's causing your error.

You need to take a step back and try to figure out exactly what you're trying to do, as this code doesn't make a ton of sense.

Upvotes: 1

Related Questions