Re: selecting random array elements
markspace wrote:
oc2052 wrote:
I am very new to Java and programming in general, and was hoping
someone could point me in the right direction with this. I am writing
a program consisting of a String array (the elements are lines of
text) and Id like to randomly pull an element from the array and
display it. I havent been able to figure out how to utilize the
java.util.random for this particular case. Thanks in advance for any
help
Just use "new Random()" to make a random object, then call "nextInt()"
on it to get a suitable random index.
Something like this:
package fubar;
import java.util.ArrayList;
import java.util.Random;
public class RandomArray {
public static void main( String[] args )
{
ArrayList<String> list = new ArrayList<String>();
Random rand = new Random();
String element = list.get( rand.nextInt( list.size() ) );
}
}
Or:
public class RandomGetter
{
private final Random rand = new Random();
// presumably not thread safe
private List <String> stuff = new ArrayList <String> ();
public RandomGetter()
{
// fill stuff here
}
public String getRandom()
{
return stuff.get( rand.nextInt( stuff.size() ));
}
public static void main( String [] args )
{
RandomGetter rander = new RandomGetter();
String element = rander.getRandom();
System.out.println( "Random element = \""+ element +"\"" );
}
}
--
Lew