Android 随机开关盒

Android 随机开关盒,android,Android,你好,朋友,我有两种情况,但我想随机做。当用户点击按钮,则有2种情况case0或case1随机变化。所以文本也是随机变化的 *lastImageName和lastImageName2是变量字符串 Random rand = new Random(); int newrand = rand.nextInt(1) + 1; switch(newrand) { case 0: text1.setText(lastImageName); text2.setText(lastImageN

你好,朋友,我有两种情况,但我想随机做。当用户点击按钮,则有2种情况case0或case1随机变化。所以文本也是随机变化的

*lastImageName和lastImageName2是变量字符串

Random rand = new Random();
int newrand = rand.nextInt(1) + 1;

switch(newrand) {
case 0:
    text1.setText(lastImageName);
    text2.setText(lastImageName2);
    break;
case 1:
    text1.setText(lastImageName2);
    text2.setText(lastImageName);
    break;
}

但这有时是行不通的。。兰特是多少。问题?

卸下+1。只要这样做:
intnewrand=rand.nextInt(2)

生成一个介于0(包括0)和上限(排除)之间的随机数。即,
nextInt(1)
将始终返回
0
。相反,您应该只使用:

int newrand = rand.nextInt(2);

如果您只有两个案例,则使用

boolean state = rand.nextBoolean();
text1.setText(state?lastImageName:lastImageName2);
text2.setText(state?lastImageName2:lastImageName);
对于多个,您也可以使用

Random rand = new Random();
int newrand = rand.nextInt() % count;//count = 2 for your case

switch(newrand) {
case 0:
    text1.setText(lastImageName);
    text2.setText(lastImageName2);
    break;
case 1:
    text1.setText(lastImageName2);
    text2.setText(lastImageName);
    break;
}
Random rand = new Random();
int newrand = rand.nextInt() % count;//count = 2 for your case

switch(newrand) {
case 0:
    text1.setText(lastImageName);
    text2.setText(lastImageName2);
    break;
case 1:
    text1.setText(lastImageName2);
    text2.setText(lastImageName);
    break;
}