4

I have some arrays containing Strings and I would like to select randomly an item from each array. How can I accomplish this?

Here are my arrays:

static final String[] conjunction = {"and", "or", "but", "because"};

static final String[] proper_noun = {"Fred", "Jane", "Richard Nixon", "Miss America"};

static final String[] common_noun = {"man", "woman", "fish", "elephant", "unicorn"};

static final String[] determiner = {"a", "the", "every", "some"};

static final String[] adjective = {"big", "tiny", "pretty", "bald"};

static final String[] intransitive_verb = {"runs", "jumps", "talks", "sleeps"};

static final String[] transitive_verb = {"loves", "hates", "sees", "knows", "looks for", "finds"};
Dropout
  • 13,653
  • 10
  • 56
  • 109
user3266734
  • 59
  • 1
  • 1
  • 3

4 Answers4

25

Use the Random.nextInt(int) method:

final String[] proper_noun = {"Fred", "Jane", "Richard Nixon", "Miss America"};
Random random = new Random();
int index = random.nextInt(proper_noun.length);
System.out.println(proper_noun[index]);

This code is not completely safe: one time out of four it'll choose Richard Nixon.

To quote a documentation Random.nextInt(int):

Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive)

In your case passing an array length to the nextInt will do the trick - you'll get the random array index in the range [0; your_array.length)

Nigel Tufnel
  • 11,146
  • 4
  • 35
  • 31
3

if you use List instead of arrays you can create simple generic method which get you random element from any list:

public static <T> T getRandom(List<T> list)
{
Random random = new Random();
return list.get(random.nextInt(list.size()));
}

if you want to stay with arrays, you can still have your generic method, but it will looks bit different

public static <T> T   getRandom(T[] list)
{
    Random random = new Random();
    return list[random.nextInt(list.length)];

}
user902383
  • 8,420
  • 8
  • 43
  • 63
0

Just use http://docs.oracle.com/javase/6/docs/api/java/util/Random.html#nextInt(int) along with the size of an array.

Martin Podval
  • 1,097
  • 1
  • 7
  • 16
0

If you want to cycle through your arrays you should put them into an array. Otherwise you need to do the random pick for each one separately.

// I will use a list for the example
List<String[]> arrayList = new ArrayList<>();
arrayList.add(conjunction);
arrayList.add(proper_noun);
arrayList.add(common_noun);
// and so on..

// then for each of the arrays do something (pick a random element from it)
Random random = new Random();
for(Array[] currentArray : arrayList){
    String chosenString = currentArray[random.nextInt(currentArray.lenght)];
    System.out.println(chosenString);
}
Dropout
  • 13,653
  • 10
  • 56
  • 109