Coding Help Cannot Make Random Images Being Chosen

//master variables  
PImage[] randomIMG = new PImage[5];
int numOfIMG;
int rand = 0;
PImage image1,image2,image3,image4,image5;
float height = 100;
float width = 50;
float length = 150;
//imageONE = loadImage ("imageNOW.jpg"); //lines 5-7 are the instances of three different image variables that share the same image file 
//imageTWO = loadImage ("imageNOW.jpg"); 
//imageTHREE = loadImage ("imageNOW.jpg"); 

void setup() {
  
  size(400,400);
  
  randomIMG[0] = loadImage("image1.jpg");
  randomIMG[1] = loadImage("image2.jpg");
  randomIMG[2] = loadImage("image3.jpg");
  randomIMG[3] = loadImage("image4.jpg"); 
  randomIMG[4] = loadImage("image5.jpg");
  
  for (int i = 0; i < numOfIMG; i++) { 
    rand = (int)random(5);
    randomIMG[i] = loadImage("image"+ randomIMG[i]+".jpg");
    //print(randomIMG[i]);
    image(randomIMG[i],40,70);
    print(randomIMG[i]);
 }
}
void draw() { 
  background(0);
  fill(150);
  rect(75,50,height, width);
  rect(230,50,height, width);
}

void mousePressed() { 
  link("http://processingjs.org"); 
}

This is the code that I have as follows. I would like to create something that allows me to have a random image be displayed upon running the program that is randomly chosen from an element in the array (image in the list).

I am having trouble displaying the image and getting a random number correspondent to the chosen image to display such image.

I am a COMPLETE novice to processing so please be a little easy.

1 Like

This is a good start. If I understand correctly, you’re correctly loading your images here:

randomIMG[0] = loadImage(“image1.jpg”);
randomIMG[1] = loadImage(“image2.jpg”);
randomIMG[2] = loadImage(“image3.jpg”);
randomIMG[3] = loadImage(“image4.jpg”);
randomIMG[4] = loadImage(“image5.jpg”);

(By the way, try to format your code when you post it.)

But then I’m not sure what you’re doing with this for loop:

for (int i = 0; i < numOfIMG; i++) {

You don’t need to loop over your array to pick one from it. You can probably just do something like this:

int randomIndex = (int) random(5);
PImage myChosenImage = randomIMG[randomIndex];

Also note that you’re clearing out the images by drawing a background color in the draw() function. If you want your image to display, you’ll have to redraw it (or get rid of the background).

2 Likes