Kleigh Kleigh - 1 year ago 91
Java Question

How to randomly assign 2 character codes in Java

I have two groups that can be assigned to a participant in my program that are denoted in an enum as "RG" and "NP". I want to assign these groups randomly. Is there a way to do this in java?

For example, when I randomly generated the participant's ID (which I'm currently just writing out to a file), I did this:

Random rndbid = new Random();
int msDBID = 10 + rndbid.nextInt(90);

Is there something similar to that, that would enable me to do the same thing but instead of randomly generating an int, it would randomly generate either a "RG" or "NP"?

Please let me know if you need clarification. Thanks in advance!

EDIT: I am very new to Java, so please be as explanatory as possible! I am learning as I go. Thanks!!

Answer Source

You can use this method :

public String flip(){
    Random randomNum = new Random();
    int result = randomNum.nextInt(2);
    if(result == 0){
        return "RG";
    } else {
        return "NP";
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download