简体   繁体   English

如何从单独的类文件中随机选择两个枚举值

[英]How do I randomly choose between two enum values from a seperate class file

So I need to create one class with an enum in it, then use a second class to randomly select one of those enum values and do that as many times as the user wants. 所以我需要在其中创建一个带有枚举的类,然后使用第二个类随机选择其中一个枚举值并按照用户的需要多次执行。

Here's the main code 这是主要代码

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);
      }

and then here's the enum code 然后这是枚举代码

    public class Coin{

public enum CoinEnum {
        HEADS,TAILS;
    }
}

I cut out some stuff because it was unneeded. 我删掉了一些东西,因为它不需要。 I think I have the general idea on how to randomly select, you can see I already wrote a quick calculation on how to do if there wasn't an enum value but I have no idea how to access the enum values from my main program, I tried making the class a package but that didn't work, I'm just not sure how. 我想我对如何随机选择有一般的想法,你可以看到我已经写了一个关于如果没有枚举值如何做的快速计算,但我不知道如何从我的主程序访问枚举值,我试着让这个类成为一个包但是没有用,我只是不确定如何。 Any help would be great. 任何帮助都会很棒。

Thanks 谢谢

The following code should work - randomly generate HEAD or TAIL enum; 以下代码应该可以工作 - 随机生成HEAD或TAIL枚举; comments added to the code. 评论添加到代码中。 Edited to change this to a working standalone example. 编辑将其更改为一个独立的工作示例。

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;
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM