1

How do I return the name value of enumerated object by its specific ordinal number?

Here's my code:

import java.util.*

public class Enumarating {
      enum Animals {bunneh , sheep , horse , cow , supercow}

      public static void main(String [] args) {
          Random rand = new Random();
          Animals animal;
      }
}

I will define the random range to 4, and let's say I get number 2. Then I want "horse" to be printed. What method should I use?

QED
  • 9,803
  • 7
  • 50
  • 87
naor.z
  • 107
  • 8

2 Answers2

0

The code is:

Animals.values()[rand.nextInt(Animals.values().length)];

[edit]

Animals.values() // gets an array with all the enum constants
rand.nextInt(x) // returns a random integer between 0 (inclusinve) and x (exclusive)
Timothy Truckle
  • 15,071
  • 2
  • 27
  • 51
0
Animals values[] = Animals.values()

This will give you your value:-

values[rand.nextInt(your_range)]
Raj Hassani
  • 1,577
  • 1
  • 19
  • 26