2014-09-06 134 views
-6

如何为变量“myVariable”赋值为“a”,“b”或“c”的随机值?我尝试以下,但得到的几个误区:yo如何随机给变量赋值?

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

提供必要的代码重现您的确切错误。另外,不要忘记给你的变量提供一个默认值。 – 2014-09-06 17:22:42

+1

我不认为'r.next()%33'返回一个字符串。 – 2014-09-06 17:24:03

+0

r.next()的大小参数在哪里?不,它不会返回一个字符串,也不会将您的switch语句写成使用字符串。阅读javadoc? – keshlam 2014-09-06 17:24:40

回答

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

这使一个差不多出现每个值的概率相等。

0
Random rand = new Random(); 
int min = 97; // ascii for 'a' 
int randomNum = rand.nextInt(3) + min; 
char myVariable = (char)randomNum; 
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)]; 
    } 
}