如何随机为变量赋值?

时间:2014-09-06 17:21:53

标签: java string variables random

如何为变量" myVariable"分配随机值?要么是" a"," b",要么" c"?我正在尝试以下方法,但得到了几个错误:

Random r = new Random();
String i = r.next()%33;
switch (i) {
  case 0:
    myVariable = "a";
  case 1:
    myVariable = "b";
  case 2:
    myVariable = "c";
}

4 个答案:

答案 0 :(得分:4)

你应该使用

r.nextInt(3);

从0-2范围内得到一个数字。所以,

switch(r.nextInt(3)) {
  case 0: myVar = "a"; break;
  case 1: myVar = "b"; break;
  case 2: myVar = "c"; break;
}

答案 1 :(得分:0)

通常情况下,当涉及到一个随机数时,我只是检查它是否在一个范围内,例如..

Random random = new Random();
int output = random.next(100);

if(output > 0 && output < 33) {
    myVariable = "a";
}
else if(output >= 33 && output < 66) {
    myVariable = "b";
}
else {
    myVariable = "c";
}

这给出了出现的每个值的几乎概率。

答案 2 :(得分:0)

Random rand = new Random();
int min = 97; // ascii for 'a'
int randomNum = rand.nextInt(3) + min;
char myVariable = (char)randomNum;

答案 3 :(得分:0)

所有好的答案,但这里有一个不同的答案:

class Randy {
    private final String[] POSSIBLE_VALUES = { "foo", "bar", "baz", ... };
    private final Random random = new Random();

    String getRandomValue() {
        return POSSIBLE_VALUES[random.nextInt(POSSIBLE_VALUES.length)];
    }
}