Kleigh Kleigh - 6 months ago 10
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);
stringB.append(String.valueOf(msDBID));
stringB.append("\t");


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

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