所以我需要创建一个带有枚举的类,然后使用第二个类随机选择其中一个枚举值,并按照用户的需要多次执行。
这是主要代码
while (loop){
System.out.println("Enter the number of times you want to toss the coin, enter '0' to end the program: ");
num = s.nextInt();
int tails = 0;
int heads = 0;
if (num == 0){
loop = false;
continue;
}
else if (num < 0){
System.out.println("That's a negative number");
continue;
}
for (int count = 0; count < num; count++)
{
if (rand.nextInt(2) == 0)
tails = tails + 1;
else
heads = heads + 1;
}
System.out.println("Heads: " + heads + " Tails: " + tails);
}
然后这是枚举代码
public class Coin{
public enum CoinEnum {
HEADS,TAILS;
}
}
我删掉了一些东西,因为它不需要。 我想我对如何随机选择有一般的想法,你可以看到我已经写了一个关于如果没有枚举值如何做的快速计算,但我不知道如何从我的主程序访问枚举值,我试着让这个类成为一个包但是没有用,我只是不确定如何。任何帮助都会很棒。
由于
答案 0 :(得分:0)
以下代码应该可以工作 - 随机生成HEAD或TAIL枚举;评论添加到代码中。编辑将其更改为一个独立的工作示例。
public class CoinEnumDemo {
public static void main(String[] args) {
// print 10 random values
for (int i = 0; i < 10; i++) {
int val = (int) Math.round(Math.random());
System.out.println(CoinEnum.values()[val]);
}
}
enum CoinEnum {
HEAD, TAIL;
}
}