简体   繁体   中英

String array in java random

String [] rnum = {"Black", "Red", "Black", "Red", "Black", "Red", "Black","Red",
"Black", "Red", "Black", "Red", "Black", "Red", "Black", "Red","Black", "Red", "Green"}; 
int A = rnum.length; 
//the "Math.random() method will get you a random color

int random = (int) (Math.random() * A);  
//randomize the strings  
String Color = rnum[random];

How do i say "if color = black then do this" or same for green or same for red"

You mean...

if(Color.equals("Black")) {
   // then do this
} else if(Color.equals("Red"){
   // then do this
}

or even (In Java >= 1.7)

switch(Color) {
   case "Black":
       // then do this
       break;
   case "Red":
       // then do this
       break;
}

Color should not be capitalized, since that can be a Java class name.

For this purpose you can use a ternary operator (shortened if-else):

String color = ( rnum[random].compareTo("Black") == 0 ? ** do something here ** : ** do something if the color is not "Black" ** );

or:

String color = "";
if(rnum[random].compareTo("Black") == 0) {
    // do stuff
}
else {
    // it's not black. do other stuff.
}

With red and green, just replace "Black" with "Red" , or "Green" .

Using java equals method for each color is the simplest way.

http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#equals%28java.lang.Object%29

Others said the method to decide equality, I would add up something about the algorithm.

Consider adding weight of colours, I see Red and Black appear 9 times while Green appears once. I would add an object containing the name of the colour and the weight you want to apply. Like {"Green", 1}, {"Red", 9}, {"Black", 9}.

Sum up the weights and order the colours in some way and decide where the random number fell.

It would make more clean code and nicer solution.

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