2014-04-01 41 views
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]; 

String數組,我怎麼說,「如果顏色爲黑色,然後做這個」或同爲綠色或同爲紅色的」在Java中隨機

+0

color.equals(「Black」) –

+1

您可以爲此使用枚舉。但是如果你不想使用枚舉,你會發現這是非常罕見的情況之一,當使用'=='而不是'.equals'來比較字符串時。 –

+0

我同意大衛華萊士,枚舉仍然是最好的方式,還可以與枚舉巫術(在Java 7之前),如果一些顏色被添加到用例,沒有太多的工作來重構代碼。 – chillworld

回答

0

Color不應該大寫,因爲這可以是一個Java類。名字

爲了這個目的,你可以使用一個三元操作符(縮短的if-else):

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

或:

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

使用紅色和綠色,只需將"Black"替換爲"Red""Green"即可。

5

你的意思是......

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

甚至(在Java> = 1.7)

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

請注意,可以從java 7開始使用字符串。舊版本不支持這一點。 – chillworld

0

其他人說的方法來決定的平等,我想補充了一些有關的算法。

考慮增加顏色的重量,我看到紅色和黑色出現9次,而綠色出現一次。我會添加一個包含顏色名稱和要應用的重量的對象。像{「綠色」,1},{「紅色」,9},{「黑色」,9}。

總結權重並以某種方式排列顏色並決定隨機數下降的位置。

這將使更多的乾淨的代碼和更好的解決方案。