我必须从数组中随机选择三个位置,然后将三个 TextView 上的文本设置到这些位置。我怎样才能避免选择相同的两件商品的风险?我研究了几种方法,但似乎都不适用,或者我太缺乏经验而无法使用它们。非常感谢任何帮助!
这是我到目前为止所得到的。
qs2 = qs.clone();
//Calling the TextViews and Image Views from motivatorscreen.xml
Question1 = (TextView) findViewById(R.id.question1);
Question2 = (TextView) findViewById(R.id.question2);
Question3 = (TextView) findViewById(R.id.question3);
int randomIndex = new Random().nextInt(qs2.length);
int randomIndex2 = new Random().nextInt(qs2.length-1);
int randomIndex3 = new Random().nextInt(qs2.length-2);
String randomQuestion = qs2[randomIndex];
String randomQuestion2 = qs2[randomIndex2];
String randomQuestion3 = qs2[randomIndex3];
Question1.setText(randomQuestion);
Question2.setText(randomQuestion2);
Question3.setText(randomQuestion3);
}
但是对于代码,就像现在一样,存在两次选择相同内容的风险,我想摆脱它。关于如何实现它的任何提示?
最佳答案
声明全局变量 像这样使用 do-while
int randomIndex=0,randomIndex2 =0,randomIndex3 =0; //declare global
randomIndex = new Random().nextInt(qs2.length);
do{
randomIndex2 = new Random().nextInt(qs2.length);
}while(randomIndex ==randomIndex2 );
do{
randomIndex3 = new Random().nextInt(qs2.length);
}while(randomIndex2 ==randomIndex3 );
关于java - 如何从数组中选择3个位置,选择后删除每个位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53943428/