java - 从java中的字符串数组中选择一个随机项目

标签 java arrays random

<分区>

我有一些包含字符串的数组,我想从每个数组中随机选择一个项目。我怎样才能做到这一点?

这是我的数组:

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

最佳答案

使用 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):

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

在您的情况下,将数组长度传递给 nextInt 将达到目的 - 您将获得 [0; 范围内的随机数组索引; your_array.length)

关于java - 从java中的字符串数组中选择一个随机项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21726033/

相关文章:

linux - 我明白/dev/urandom 了吗?

java - 使用 Xuggler 设置视频中每帧的持续时间

java - java字符串中的特殊字符

java - Java方法声明中的方括号是什么意思?

javascript - 如何在 AngularJS 中的后续请求中正确存储本地数组

c - 将多维数组与通用函数一起使用

arrays - 给定一个二维矩阵,其中每列占用的 block 范围,找到每行占用的 block 数

c# - 如何生成唯一订单号?

python - 排除 random.choice() 生成的特定字符

java - (Sum) jtext 中的查询结果