我有一些包含字符串的数组,我想从每个数组中随机选择一个项目。我怎么能做到这一点?
以下是我的数组:
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"};
答案 0 :(得分:15)
使用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之间均匀分布的int值 (包括)和指定值(不包括)
在你的情况下,将一个数组长度传递给nextInt
就行了 - 你将得到[0; your_array.length)
答案 1 :(得分:2)
如果您使用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)];
}
答案 2 :(得分:0)
答案 3 :(得分: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);
}