2016-02-17 113 views
0

我已经写了一个方法来生成一个数组的随机值,但我不知道如何生成另外两个值,因为它们最终都只是相同的数字。 这里是我写的,但它只是崩溃......如何从一个数组中生成3个随机值

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); 

}

如果有人知道更简单的方式来做到这一点的帮助感激:)

+0

您需要创建随机数的3倍,仅未1次。 – Atri

+0

那么,因为所有的3都是使用'group_topics [index]'并行提取的,不需要改变它们之间的'index'的值,*为什么*你会期望不同的值? – Andreas

回答

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]; 
相关问题