JAVA:按顺序值返回枚举的对象名称

naor.z

如何通过枚举对象的特定序号返回其名称值?

这是我的代码:

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。然后,我希望打印“马”。我应该使用哪种方法?

蒂莫西·卡特尔(Timothy Truckle)

代码是:

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)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章