Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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,

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; 

    }

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.

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
105 views
Welcome To Ask or Share your Answers For Others

1 Answer

Just clubsArray[new Random().nextInt(clubsArray.length)] would work

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...