【问题标题】:String array in java randomjava中的随机字符串数组
【发布时间】:2014-05-13 00:08:41
【问题描述】:
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];

我怎么说“如果颜色 = 黑色,则执行此操作”或绿色相同或红色相同”

【问题讨论】:

  • color.equals("Black")
  • 您可以为此使用枚举。但是如果你不想使用枚举,你会发现这是非常罕见的情况之一,可以使用== 而不是.equals 来比较字符串。
  • 我同意大卫华莱士的观点,枚举仍然是最好的方式,也可以使用枚举进行巫术(在 java 7 之前),如果在用例中添加了一些颜色,重构代码的工作并不多。

标签: java arrays random


【解决方案1】:

你是说……

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

【讨论】:

  • 请注意,从 java 7 开始可以使用字符串进行切换。旧版本不支持此功能。
【解决方案2】:

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"

【讨论】:

    【解决方案3】:

    对每种颜色使用java equals方法是最简单的方法。

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

    【讨论】:

      【解决方案4】:

      其他人说判断相等的方法,算法我补充一下。

      考虑增加颜色的权重,我看到红色和黑色出现了 9 次,而绿色出现了一次。我会添加一个包含颜色名称和您要应用的重量的对象。比如 {"Green", 1}, {"Red", 9}, {"Black", 9}。

      总结权重并以某种方式对颜色进行排序,然后决定随机数落在哪里。

      它会产生更简洁的代码和更好的解决方案。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-06-26
        • 2016-01-04
        • 1970-01-01
        • 2018-09-20
        • 2014-02-09
        • 2017-05-20
        相关资源
        最近更新 更多