Choosing a random element from an array of strings in java

I have several arrays containing strings, and I would like to randomly select an element from each array. How can i do 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"};
+3
source share
4 answers

Use the method Random.nextInt(int):

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 of four times he will choose Richard Nixon.

To bring the documentation Random.nextInt(int):

Returns a pseudo-random uniformly distributed int value between 0 (inclusive) and the specified value (excluding)

In your case, passing the length of the array to nextIntwill lead to a trick - you will get the index of a random array in the range[0; your_array.length)

+14
source

List , , :

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

, ,

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

}
+1

If you want to loop through your arrays, you must put them in an array. Otherwise, you need to make an arbitrary choice for each 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);
}
0
source

All Articles