如何爲變量「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";
}
如何爲變量「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";
}
您應該使用
r.nextInt(3);
從0-2範圍內得到的數字。所以,
switch(r.nextInt(3)) {
case 0: myVar = "a"; break;
case 1: myVar = "b"; break;
case 2: myVar = "c"; break;
}
通常情況下,當它涉及到一個隨機數,我就檢查它是否是一個範圍內,例如..
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";
}
這使一個差不多出現每個值的概率相等。
Random rand = new Random();
int min = 97; // ascii for 'a'
int randomNum = rand.nextInt(3) + min;
char myVariable = (char)randomNum;
所有很好的答案,但這裏有一個不同:
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)];
}
}
提供必要的代碼重現您的確切錯誤。另外,不要忘記給你的變量提供一個默認值。 – 2014-09-06 17:22:42
我不認爲'r.next()%33'返回一個字符串。 – 2014-09-06 17:24:03
r.next()的大小參數在哪裏?不,它不會返回一個字符串,也不會將您的switch語句寫成使用字符串。閱讀javadoc? – keshlam 2014-09-06 17:24:40