-2

I'm new to Java and had a newbie question. I am trying to randomly retrieve an enum value as below.

public enum ParkedCar {
     car1(....),
     car2(....);
......
}

Random rand = new Random();
int i = 1 + rand.nextInt(5);
String s = "car" + i;
ParkedCar car = ParkedCar.$s;

However, unlike in Perl where we can use $s to insert the value of s, $s is not valid in Java. What is the Java equivalent if one exists?

Thanks!

stackoverflow
  • 399
  • 2
  • 14

3 Answers3

4

You want Enum.valueOf(String s):

String s = "car" + i;
ParkedCar car = ParkedCar.valueOf(s);

This looks up the enum instance by its name.

Note that if a matching instance isn't found this method will throw a IllegalArgumentException

Bohemian
  • 412,405
  • 93
  • 575
  • 722
0

Java is very different than Perl.

You can't build a variable name with a string and then reference it.

(You actually can do it with reflection, but that makes zero sense here)

You can get a random enum value like this:

Random rand = new Random();
ParkedCar[] carArray = ParkedCar.values();
int index = rand.nextInt(carArray.length);
ParkedCar randomCar = carArray[index];
jahroy
  • 22,322
  • 9
  • 59
  • 108
0

try: ParkedCar c=ParkedCar.values()[new Random().nextInt(ParkedCar.values().length)];

Ray Tayek
  • 9,841
  • 8
  • 50
  • 90