1
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"

3
  • color.equals("Black") Commented Apr 1, 2014 at 23:54
  • 1
    You could use an enum for this. But if you don't want to use an enum, you'll find that this is one of the very rare cases when it's OK to use == instead of .equals to compare Strings. Commented Apr 2, 2014 at 0:03
  • I agree with David Wallace, Enum is still the nicest way, also witching with enums is possible(before java 7) and if some color is added to use case, not much work to refactor the code. Commented Apr 2, 2014 at 2:26

4 Answers 4

5

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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Take attention that switch with Strings is possible from java 7. Older versions do not support this.
0

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".

Comments

0

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.