你好朋友我有2种情况,但我想随便做。当用户单击按钮时,有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;
}
但有时候不工作......兰特是什么。问题
答案 0 :(得分:1)
Random rand = new Random();
int a = 0;
int b = 1;
int c = random.nextBoolean() ? a : b;
答案 1 :(得分:0)
删除+1。就这样做:int newrand = rand.nextInt(2);
答案 2 :(得分:0)
Random#nextInt(int)
生成一个介于0和0之间的随机数。即,nextInt(1)
将始终返回0
。相反,你应该使用:
int newrand = rand.nextInt(2);
答案 3 :(得分:0)
如果您只有两个案例,请使用
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;
}