Is there a way to pick a random object from an array of objects?
I have tried a few ways that I could think of but none work.
I want to use a function in the random class (all classes will have the same function but different returns).
I should have mentioned i am trying to return an image, and each time i try to return a random image it doesnt return anyting (“null”)
Here is some of my code I am having the problem with:
Car car;
Ford ford;
Mazda mazda
Fiat fiat
Rover rover
Car carlist[] = {ford,fiat,mazda,rover}
public void paint(){
//this displays an image every 128 pixles
for (int i = 0;i<Width;i+=128){
for(int j=128; j<Height;j+=128){
// this draws the image (the image is declaired in each car's class as getImage)
g.drawImage((car.carList[rand.nextInt(5)]).getImage(), i, j , this);
}
}
The code works if i put an object in (instead of carcarList[rand.nextInt(5)])).
Each of the cartypes extend Cars.
Assuming
yourListis the array of your objects, use this single line: