Reputation: 11
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"
Upvotes: 1
Views: 132
Reputation: 813
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.
Upvotes: 0
Reputation: 11440
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;
}
Upvotes: 5
Reputation: 1
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
Upvotes: 0
Reputation: 2276
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"
.
Upvotes: 0