从数组中选择一个随机值 [英] Select a random value from an Array
问题描述
我有一个数值数组,我想从该数组中随机选择一个值,然后将其插入到 int
变量中.
I have an Array of number values, and I want to randomly select a value from in that array and then insert it in to an int
variable.
我不确定您需要查看什么代码.所以,
I'm not sure what code you will need to see. So,
这是我用来生成 13 个数字 (1-13) 并将它们插入到数组中的 for
循环.
Here is the for
loop that I'm using to generate 13 numbers (1-13) and insert them in to the Array.
int clubsArray [];
clubsArray = new int [13];
for(int i = 0; i < clubsArray.length; i++) {
clubsArray[i] = i +1;
}
这很好用,但现在我需要从该数组中选择例如 2 个随机值(然后将其插入到稍后使用的变量中.
That works fine, but now I need to select for example 2 random values from in that array (and then insert it in to a variable to be used later on.
我在许多网站上环顾四周,看到诸如 ArrayList
之类的东西,以便将值插入到数组中,然后使用 Random generator = new Random()
从数组中选择值,然后 .remove()
从数组中删除它.但是当我使用它时它不起作用.
I've looked around on many websites and I've seen things like ArrayList<String>
in order to insert values in to an Array and then use Random generator = new Random()
to select the value from the array and then .remove()
to remove it from the array. But when ever I have used that it doesn't work.
推荐答案
只要 clubsArray[new Random().nextInt(clubsArray.length)]
就可以了
或者要随机化元素的顺序,使用List>clubsList=Arrays.asList(clubsArray);Collections.shuffle(clubsList);
.
Or to randomize the order of elements, use List<?> clubsList=Arrays.asList(clubsArray); Collections.shuffle(clubsList);
.
这篇关于从数组中选择一个随机值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!