Not too sure if this is the right place to post this, so if it isn't, I apologize. Still figuring out my way around here.
Anyways, what is the best way to grab a random element from an array? Truly needs to be as close to random as possible.
Welcome to the Java Programming Forums
The professional, friendly Java community. 21,500 members and growing!
The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.
>> REGISTER NOW TO START POSTING
Members have full access to the forums. Advertisements are removed for registered users.
Not too sure if this is the right place to post this, so if it isn't, I apologize. Still figuring out my way around here.
Anyways, what is the best way to grab a random element from an array? Truly needs to be as close to random as possible.
Blackjack
Use the Random class's method to choose an index value between 0 and the length of the array-1
If you don't understand my answer, don't ignore it, ask a question.
Blackrabbitjack (March 21st, 2012)
Would this be the proper way to use this utility?
public void randomGen(String[] x) { Random rangen = new Random(); int rand = rangen.nextInt(x.length-1); }
Blackjack
Looks like it might work. Write a loop and print out the returned value a few times to see what you get.
No need to create a new Random object everytime you want a number. Make rangen a class variable.
Then the method has one statement so you might as well use rangen inline.
If you don't understand my answer, don't ignore it, ask a question.
public void randomGen(String[] x) { int rand = rangen.nextInt(x.length-2); JOptionPane.showMessageDialog(null, "Randomly chosen word is: " + x[rand]); }
For anyone interested in this code for later, this definitely works. I have some strange assignment to my array, so I have to sub 2 instead of one, otherwise I'll occasionally get a "null" return due to the last element being, well, null =P. JOptionPane's message dialog can be subbed for a system.out.println, but I find the dialogs much nicer to look at in the long run. Thanks again, Norm, for the guidance!
EDIT: Good idea on the class variable, btw. Originally wrote it contained to see if it would work properly. Is now resting up above with all my others.
Last edited by Blackrabbitjack; March 21st, 2012 at 03:10 PM. Reason: More info
Blackjack