use*_*734 4 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"};
Run Code Online (Sandbox Code Playgroud)
Nig*_*nel 16
使用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]);
Run Code Online (Sandbox Code Playgroud)
这段代码并不完全安全:四分之一的人会选择Richard Nixon.
引用文档Random.nextInt(int):
返回伪随机,在0(包括)和指定值(不包括)之间均匀分布的int值
在你的情况下,将数组长度传递给nextInt将执行技巧 - 您将获得范围内的随机数组索引[0; your_array.length)