簡體   English   中英

Java Random中的字符串數組

[英]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];

我怎么說:“如果顏色=黑色,那么就這樣做”,或者對於綠色相同,對於紅色相同”

你的意思是...

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

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"

對每種顏色使用java equals方法是最簡單的方法。

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

其他人說,決定平等的方法,我會加一些關於算法的東西。

考慮增加顏色權重,我看到紅色和黑色出現9次,而綠色出現一次。 我將添加一個對象,其中包含顏色名稱和要應用的權重。 像{“ Green”,1},{“ Red”,9},{“ Black”,9}。

對權重求和,並以某種方式對顏色進行排序,然后確定隨機數的位置。

這將使代碼更簡潔,解決方案更好。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM