从数组中选择一个随机值 [英] Select a random value from an Array

查看:253
本文介绍了从数组中选择一个随机值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些值的数组,我想随机数组中选择一个值,然后在一个 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.

我不知道什么code,你需要看到的。因此,

I'm not sure what code you will need to see. So,

下面是我使用来产生13号(1-13),并在该阵列插入它们的循环。

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&LT;为了在一个阵列插入值,然后用<$ C ;字符串&GT $ C>随机发生器=新的随机()从数组中选择值,然后一个.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 [新的随机()。nextInt(clubsArray.length)] 将工作

或者随机化元素的顺序,使用列表&LT;&GT; clubsList = Arrays.asList(clubsArray); Collections.shuffle(clubsList);

Or to randomize the order of elements, use List<?> clubsList=Arrays.asList(clubsArray); Collections.shuffle(clubsList);.

这篇关于从数组中选择一个随机值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆