TextView textView1 = (TextView) findViewById(R.id.textView1);
int randomArray = (int) (Math.random() *4);
textView1.setText(questions[randomArray][0]);
使用上面的代码(使用android studio开发应用程序)我可以从我的数组中生成一个随机问题,如下所示。
String[][] question= new String[20][5];
{
question[0][0] = "what is my name?";
question[0][1] = "Mark";
question[0][2] = "Steven";
question[0][3] = "Alan";
question[0][4] = "Bob";
question[1][0] = "what is my age?";
question[1][1] = "30";
question[1][2] = "31";
question[1][3] = "32";
question[1][4] = "33";
}
下面的代码显示了我如何分配按钮的答案,以便每次随机分配到不同的按钮:
Button button2 = (Button)findViewById(R.id.button2);
int randomArray1 = (int) (Math.random() *4);
button2.setText(questions[randomArray][randomArray1+1]);
Button button3 = (Button)findViewById(R.id.button3);
int randomArray2 = (int) (Math.random() *4);
button3.setText(questions[randomArray][randomArray2+1]);
Button button4 = (Button)findViewById(R.id.button4);
int randomArray3 = (int) (Math.random() *4);
button4.setText(questions[randomArray][randomArray3+1]);
Button button5 = (Button)findViewById(R.id.button5);
int randomArray4 = (int) (Math.random() *4);
button5.setText(questions[randomArray][randomArray4+1]);
+1只表示问题不会放在按钮中。我想要的帮助就是如何从选项中删除随机选择,这样我就不会有2,3或4个按钮说史蒂夫或30等问题。
答案 0 :(得分:0)
您可以将字符串放在ArrayList中,随机化ArrayList,然后只需从每个按钮的ArrayList中删除顶部条目。
mButton1.setText(mArrayList.remove(0));
mButton2.setText(mArrayList.remove(0));
答案 1 :(得分:0)
如果您将要显示的答案放在ArrayList
中,则可以使用Collections.shuffle()
简单地随机化顺序。然后你只需将答案逐一放入他们的视图中,他们就会自动为你洗牌。通过这种方式,您不必担心重复,因为您只需要在列表中拥有每个答案的一个副本。因此,只需将它们逐个放入新随机化顺序的视图中即可。
检查一下......这里是如何运作的:
ArrayList<String> answers = new ArrayList<>();
answers.add("dave");
answers.add("steve");
answers.add("john");
answers.add("carl");
for(int i=0; i<answers.size(); i++) {
//answers in their original order
Log.d("ANSWERS", answers.get(i));
}
Collections.shuffle(answers, new Random());
for(int i=0; i<answers.size(); i++) {
//answers are now in a randomized order
Log.d("SHUFFLED ANSWERS", answers.get(i));
}