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

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

}

如果有人知道更简单的方法来执行此操作,我们将不胜感激:)

最佳答案

创建 3 个不同的随机数:

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

现在使用这 3 个随机数,而不是仅生成一次的相同索引

<小时/>
randomOne = group_topics[index1];
randomTwo = group_topics[index2];
randomThree = group_topics[index3];

关于java - 如何从数组生成 3 个随机值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35447463/

相关文章:

java - 设计决策 : extending an interface vs. 新界面

java - Spring:这个模式是线程安全的吗?

java - 尝试动态定义布局

java - ChangeListener 未触发

java - 某些组件的用途

javascript - 按值排序对象未按预期工作

java - 使用 jmapframe 在 map 上制作动画 - geotools

python - 如何查找 numpy 数组中的每条步行

python - 如何将 numpy 数组(实际上是 BGR 图像)转换为 Base64 字符串?

javascript - 无法复制多维数组