【问题标题】:JAVA: returning enumerated object name by the ordinal valueJAVA:按序数值返回枚举对象名称
【发布时间】:2016-10-28 09:31:40
【问题描述】:

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

这是我的代码:

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。然后我想打印“马”。 我应该使用什么方法?

【问题讨论】:

标签: java enums


【解决方案1】:

代码是:

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)

【讨论】:

  • 你能解释一下你在括号里做了什么吗?
【解决方案2】:
Animals values[] = Animals.values()

这会给你你的价值:-

values[rand.nextInt(your_range)]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多