2014-03-28 86 views
0

创建一个枚举后,我想分配一个随机值并将其作为参数发送给函数,但是我遇到了问题。作为参数的随机枚举

public enum TGate 
{ 
    A, B, C, D 
} 

public class Parking 
{ 
    TGate gate; 
    gate=TGate.C; 

    public Parking(TGate gate) 
    { 
    switch gate..... 
    } 
} 

我希望有人能帮助我。 感谢

+1

您可以添加能力为枚举对象的一部分 - 看看http://stackoverflow.com/questions/8114174/how-to-randomize -enum-elements – mtripp100

+0

我看不到你,有什么问题? – 2014-03-28 10:02:54

回答

0

你可以这样写:

TGate gate; 
gate = TGate.values()[(int)(Math.random()*TGate.values().length)]; 

,并通过这门功能可按。

0

您可以这样试试:

public class Example { 

    public static void main(String[] args) { 
     new Parking(TGate.values()[(int) (Math.random() * TGate.values().length)]); 
    } 
} 

enum TGate { 
    A, B, C, D 
} 

class Parking { 

    private final TGate gate; 

    public Parking(TGate gate) { 
     this.gate = gate; 
    } 
}