Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I join the names of 2 variables in a method? [duplicate]

Tags:

java

libgdx

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?

like image 525
Erick Adam Avatar asked Dec 11 '22 10:12

Erick Adam


2 Answers

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)

like image 74
YCF_L Avatar answered Mar 25 '23 04:03

YCF_L


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 ...

}
like image 34
Amr Avatar answered Mar 25 '23 03:03

Amr