2016-10-28 106 views
1

如何通過其特定序號返回枚舉對象的名稱值?JAVA:通過序號值返回枚舉對象名稱

這裏是我的代碼:

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號。然後我想打印的「馬」。 我應該使用什麼方法?

+4

可能重複:HTTP:/ /stackoverflow.com/q/609860/2580773 –

+0

你想要http://stackoverflow.com/a/19277247/785663 – mabi

回答

0

的代碼是:

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) 
+0

你能解釋一下你在括號裏做了什麼嗎? –

+0

瞭解!非常感謝你 –

0
Animals values[] = Animals.values() 

這會給你你的價值: -

values[rand.nextInt(your_range)]