user1159424
user1159424

Reputation: 99

Pick and use a random class from an array

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(but they all return an Image they just have different paths)).

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 (if i put in car.ford instead of carcarList[rand.nextInt(5)])). Each of the cartypes extend Cars.

Upvotes: 0

Views: 447

Answers (2)

Clockwork-Muse
Clockwork-Muse

Reputation: 13056

Sure you can get a random element, although I recommend one of the collections, and using an interface:

public interface Car {
    public Image getImage();
}

public class main {

    public static void main(String...args) {

        // repeat for other types, or define non-anonmyous versions
        Car ford = new Car() {
                      private Image fordImage = new Image(<location>);
                      public Image getImage() {
                                return fordImage;
                      }
                    };

        List<Car> carList = new ArrayList<Car>();
        carList.add(ford);

        // Gets a random car
        Car randomCar = carList.get(random.nextInt(carList.size()));

    }
}

Upvotes: 1

DNA
DNA

Reputation: 42597

You are already using the right approach to randomly select items from an array:

String[] a = {"a","b","c"};
Random rand = new Random();
System.out.println(a[r.nextInt(3)]);

But as Brian Roach pointed out, you have to have something in the array to select...

Upvotes: 1

Related Questions