Re: [問題] 隨機產生列舉物件的方法?

看板java作者 (godfat 真常)時間18年前 (2007/08/28 17:49), 編輯推噓1(100)
留言1則, 1人參與, 最新討論串3/3 (看更多)
※ 引述《kennyliao (aggressive)》之銘言: : public Modifier a_random_modifier() { : int index=(int)(Math.random()*Modifier.values().length); ^^^^^^^^ : return Modifier.values()[index]; : } 我不知道有 values 這種東西,用 reflection 硬幹了一份 XD 只是覺得 java 檢查實在是有夠嚴格,應該不會有錯的地方也要聲明 流程也在 compile time 檢查﹍ import static java.lang.System.out; import java.util.Random; import java.lang.reflect.*; enum Modifier{ NORMAL(1.0), VERY(2.0), MORE_OR_LESS(0.5); private static Modifier[] data_; static{ Class self = null; // variable self might not have been initialized try{ self = Class.forName("Modifier"); }catch(Exception e){out.println("must be typo: " + e);} Field[] fields = self.getFields(); Modifier.data_ = new Modifier[fields.length]; int i = 0; for(Field f: fields){ try{ data_[i++] = (Modifier)f.get(self); }catch(Exception e){out.println("must be typo: " + e);} } } private final double value; private Modifier(double value){ this.value = value; } public static Modifier pick(int pos){ return Modifier.data_[pos]; } public double getValue(){ return value; } } public class EnumTest{ public static void main(String[] args){ for(int i=0; i<10; ++i) out.println(pick().getValue()); } static Modifier pick(){ return Modifier.pick(Math.abs(new Random().nextInt()) % 3); } } -- In Lisp, you don't just write your program down toward the language, you also build the language up toward your program. 《Programming Bottom-Up》- Paul Graham 1993 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 61.218.90.242

08/29 23:20, , 1F
enum A{aa,bb,cc} -> A.values() 由 aa,bb,cc 組成的 A[]
08/29 23:20, 1F
文章代碼(AID): #16q--u01 (java)
文章代碼(AID): #16q--u01 (java)