简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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