如何从数组中生成3个随机值

时间:2016-02-17 03:40:23

标签: java arrays

我编写了一个方法,可以生成一个数组的随机值,但我不知道如何生成另外两个因为它们最终只是相同的数字。 这是我写的,但它只是崩溃......

public void getRandomTopics() {
Random random = new Random();

int index = random.nextInt(group_topics.length);

randomOne = group_topics[index];
randomTwo = group_topics[index];
randomThree = group_topics[index];

if(randomOne.equals(randomTwo) || randomOne.equals(randomThree) || randomThree.equals(randomTwo)) {
    isEqual = true;
}
while(isEqual = true){
    randomOne = group_topics[index];
    randomTwo = group_topics[index];
    randomThree = group_topics[index];

}
topicOne = (TextView) findViewById(R.id.textView2);
topicOne.setText(randomOne);

topicTwo = (TextView) findViewById(R.id.textView3);
topicTwo.setText(randomTwo);

topicThree = (TextView) findViewById(R.id.textView4);
topicThree.setText(randomThree);

}

如果有人知道更简单的方法,那么非常感谢帮助:)

1 个答案:

答案 0 :(得分:1)

创建3个不同的随机数:

int index1 = random.nextInt(group_topics.length);
int index2 = random.nextInt(group_topics.length);
int index3 = random.nextInt(group_topics.length);

现在使用这3个随机数而不是仅生成一次的index

randomOne = group_topics[index1];
randomTwo = group_topics[index2];
randomThree = group_topics[index3];