Array of images

PImage [] fotos= new PImage [1];
int nroImg;
void setup(){
nroImg=0;
size(700,700);
for (int i=0; i<fotos.length; i++){
fotos[i]=loadImage(“mr”+i+".jpg");
}
}
void draw(){
background(0);
image(fotos[nroImg],0, 0);
fotos[nroImg].resize(700,700);
println(nroImg);
if(mousePressed==true){
nroImg=1;
}
}

This is my code, and when I run it it starts, but then I click the mouse and does not load the other image, anyone has any idea why won’t the program run? By the way, both photos are .jpg and got the same name

Hi Tati, please use the “</>” icon in the toolbar of the comment box to format your code.

With new PImage[1] you defined an array of length 1, which means that your for loop will only load 1 image. Looking at your code, pressing the mouse should actually throw an index out of bounds error, as fotos[1] will actually try and look at the second position in the array, which in your case doesn’t exist.

Try making an array of length 2?

1 Like

I hope one is mr0.jpg, the other mr1.jpg (and not the same name)

wild guess: PImage [] fotos= new PImage [2]; // use 2 here

Do you receive an Error like index out of bounds or so? It’s always important to tell us when you receive an error.

please do this in setup() and not in draw() since it needs to be done only once

1 Like

you beat me to it… :wink:

1 Like

Tati, just for fun:

Arrays:
…are just lists. Nothing fancy at all. In Java, you have to specify what ‘type’ of object this list consists of; so PImage[] means an list of images, PShape[] a list of shapes and float[] a list of floats.

When you define an array, you have to specify its length. You can make an empty array, but even then you have to say: images = new Image[0].

Anyway, so the next thing is how to access items in the list. You do this by entering a number in the “access” operator, the square brackets. This number is called the index. And, here’s the confusing bit for people starting with programming, the first position in an array is at index 0.

So:

PImage[] images;

void setup() {
  images = new PImage[3]; // creates array that can hold 3 PImage objects
  images[0] = loadImage("first.jpg");
  images[1] = loadImage("second.jpg");
  images[2] = loadImage("third.jpg");
}

Hi

Nice hints

thanks to all of you guys, I had a bad thinking about the numer [] here.

1 Like