在Java中从字符串数组中随机选择一个项目

4

我有一些包含字符串的数组,我想从每个数组中随机选择一个项目。 我该如何实现?

以下是我的数组:

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"};

请查看此链接:https://dev59.com/5nI_5IYBdhLWcg3wHfOr - Sunil Singh Bora
非常感谢你们所有人! - user3266734
4个回答

25

使用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]);

这段代码并不完全安全:四次中有一次会选择Richard Nixon。

引用文档中的Random.nextInt(int)

返回介于0(含)和指定值(不含)之间的伪随机、均匀分布的整数值

在您的情况下,将数组长度传递给 nextInt 就可以了 - 您将在范围 [0; your_array.length) 中得到一个随机的数组索引。


3
如果您使用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)];

}

0
如果您想循环遍历数组,应该将它们放入一个数组中。否则,您需要分别为每个数组进行随机选择。
// 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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接