EDIT: I'm so sorry, I need to expand. I'm using LibGDx, so my code is actually more complex.
Rock1 = new TextureRegion(texture, 5, 10);
Rock2 = new TextureRegion(texture, 6, 11);
Rock3 = new TextureRegion(texture, 7, 12);
int rannum = ran.nextInt (3)+1;
I want it to be that the rock that shows up is random.
I have a random integer called 'rannum' that is set between the bounds of 1 and 3. So I want to figure out how I can get a method that makes it so that I can combine "Rock" and "rannum" so that it can randomly return either Rock1, Rock2, or Rock3.
I'm not referring to concatenating two strings - but specifically object names.
How can I do this? Does it require using an array?
You can use an array or List like this :
TypeRock[] rocks = new TyprRock[]{Rock1, Rock2, Rock3};
or :
List<TypeRock> rocks = Arrays.asList(Rock1, Rock2, Rock3);
...then you can use Random
like this :
Random ran = new Random();
TypeRock selectedRock = rocks[ran.nextInt(rocks.length)];
or :
TypeRock selectedRock = rocks[ran.nextInt(rocks.size())];
Or like @davidxxx mention in comment, you can use Collections.shuffle(list) without Random
like this :
List<TypeRock> rocks = Arrays.asList(Rock1, Rock2, Rock3);
Collections.shuffle(rocks);
Then you can use the first value for example rocks.get(0)
If it will always be a small number of possibilities (in your case there are three possible outcomes) I recommend a switch
statement with your random number as the argument.
switch(rannum) {
case 1:
return Rock1;
break;
etc ...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With