Re: [問題] 隨機產生列舉物件的方法?
※ 引述《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
08/29 23:20, 1F
討論串 (同標題文章)
本文引述了以下文章的的內容:
完整討論串 (本文為第 3 之 3 篇):