本文介绍了如何拥有独特的随机数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这就是我如何在1到6之间生成一个唯一的no并从drawable文件夹中获取适当的图像。

This is how i am generating a unique no in between 1 to 6 and getting appropriate images from the drawable folder.

Random rand = new Random();
// n = the number of images, that start at idx 1
rndInt = rand.nextInt(6) + 1; 
String imgName = "card" + rndInt;
int id = getResources().getIdentifier(imgName, "drawable", getPackageName());
imgView.setImageResource(id);

我想要的是,我必须调用此方法7次,每次此方法都应该返回一个独特的随机号码。所以没有一个已经选择过的数字会再次出现。

What i want is, I have to call this method 7 times, and each time this method should return a unique random no. so that none of the already chosen numbers will come up again.

推荐答案

这种问题的常用方法是创建一个包含每个可能值的列表并将其随机播放(使用)。然后,每次需要值时,从列表中使用一个项目。这将确保您不会多次使用相同的值,但仍允许随机顺序。

The usual approach to this kind of problem is to create a list containing each of the possible values and shuffle it (use Collections.shuffle). You then consume one item from the list each time you need a value. This will ensure that you don't use the same value more than once but still allows for a random order.

这篇关于如何拥有独特的随机数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-27 07:28