如何按枚举对象的特定序号返回其名称值?
这是我的代码:
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;
}
}
我将随机范围定义为 4,假设我得到数字 2。然后我想要打印“horse”。 我应该使用什么方法?
最佳答案
代码是:
Animals.values()[rand.nextInt(Animals.values().length)];
[编辑]
Animals.values() // gets an array with all the enum constants
rand.nextInt(x) // returns a random integer between 0 (inclusinve) and x (exclusive)
关于JAVA:按序号返回枚举对象名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40302154/