[英]How to Generate Random Numbers using ENUM in Java
我试图使用枚举生成随机数(1到10)。 变量“ num”没有获得更新的随机值,不确定我犯了什么错误。 任何指针都会有所帮助。 谢谢。
Java代码:
enum RandomNumbers
{
ONE,
TWO,
THREE,
FOUR,
FIVE,
SIX,
SEVEN,
EIGHT,
NINE,
TEN;
public static RandomNumbers getRandom()
{
return values()[(int)(Math.random() * values().length)];
}
}
public class RandomNumbersEnum
{
public static void main(String[] args)
{
RandomNumbers randN = RandomNumbers.getRandom();
int num = 0;
if (randN.values().equals("ONE"))
num = 1;
else if(randN.values().equals("TWO"))
num = 2;
else if(randN.values().equals("THREE"))
num = 3;
else if(randN.values().equals("FOUR"))
num = 4;
else if(randN.values().equals("FIVE"))
num = 5;
else if(randN.values().equals("SIX"))
num = 6;
else if(randN.values().equals("SEVEN"))
num = 7;
else if(randN.values().equals("EIGHT"))
num = 8;
else if(randN.values().equals("NINE"))
num = 9;
else if(randN.values().equals("TEN"))
num = 10;
System.out.println("The random number is: " + num);
}
}
您可以尝试使用Java的Random类,我举一些例子:
Random r = new Random();
int number = r.nextInt(10)+1;
System.out.println(number);
之所以不起作用,是因为您的if
语句正在测试枚举所有RandomNumbers
实例的数组是否等于某个String
。 当然,不可能。 调用randN.values()
,实际上是在调用静态方法RandomNumbers.values()
,该方法与getRandom()
方法中使用的方法相同。 如果您想要一个可以比较的字符串,则randN.name()
可以工作,但这并不是一个好主意。
如果您坚持要进行比较,则应使用身份比较,例如:
int num; /* Notice I'm not prematurely assigning meaningless garbage here. */
if (randN == RandomNumbers.ONE)
num = 1;
else if(randN == RandomNumbers.TWO)
num = 2;
else if(randN == RandomNumbers.THREE)
num = 3;
else
throw new IllegalArgumentException("Unrecognized RandomNumber: " + randN);
下一步将使用switch
语句:
int num;
switch(randN) {
case ONE: num = 1; break;
case TWO: num = 2; break;
case THREE: num = 3; break;
default: throw new IllegalArgumentException();
}
您没有很好地利用枚举。 这是一种充分利用enum
类型的方法:
public enum RandomNumber {
ONE(1),
TWO(2),
THREE(3);
private final int value;
private RandomNumber(int value)
{
this.value = value;
}
public int getValue()
{
return value;
}
public static RandomNumber roll()
{
RandomNumber[] values = values();
int idx = ThreadLocalRandom.current().nextInt(values.length);
return values[idx];
}
public static void main(String... argv)
{
RandomNumber num = RandomNumber.roll();
System.out.printf("The random number is %s (%d).%n", num, num.getValue());
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.