Java 从字符串数组中选择一个随机元素?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25150199/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 23:43:41  来源:igfitidea点击:

Pick a random element from a string array?

javaarrays

提问by Logger

I've got this code, which (I hope) reads from a text file with 66 words and puts the words into an array.

我有这个代码,它(我希望)从一个包含 66 个单词的文本文件中读取并将这些单词放入一个数组中。

BufferedReader buff = null;
String wordlist=new String[66];
int i=0;

try {
    buff = new BufferedReader(new FileReader("C:\easy.txt"));
    wordlist[i] = buff.readLine();
    while(wordlist[i] != null&i<66){
        wordlist[i]=buff.readLine();
        i++;
    }
}

I want to pick a random word from the array. However trying a few things myself and looking at other questions doesn't seem to work. Any help would be appreciated

我想从数组中随机选择一个单词。然而,自己尝试一些事情并查看其他问题似乎不起作用。任何帮助,将不胜感激

回答by Abdul

Generate a random number between 0 and 65, and then use that number as the index of which String you choose.

生成一个 0 到 65 之间的随机数,然后使用该数字作为您选择的 String 的索引。

回答by David Koelle

This should work:

这应该有效:

String randomString = wordlist[(int)(Math.random() * wordlist.length)];

回答by Phil

You can create a random number generator (an instance of Random).

您可以创建一个随机数生成器(Random 的一个实例)。

Then you call the method nextInt(wordList.length) to get a random index on your array of string.

然后调用 nextInt(wordList.length) 方法来获取字符串数组的随机索引。

For example:

例如:

Random random = new Random(); int index = random.nextInt(wordList.length);

随机随机=新随机();int index = random.nextInt(wordList.length);

Then: wordList[index] to get the randomly selected string.

然后: wordList[index] 得到随机选择的字符串。

回答by Bohemian

The simplest code IMHO would be:

恕我直言,最简单的代码是:

String word = wordlist[new Random().nextInt(wordlist.length)];

回答by Zavax

One solution is to is to select a random number from the wordlist array by doing
String = randomWord = wordlist[(int)Math.random() * wordlist.length]
or
String randomWord = wordlist[(int)Math.random() * 66]

一种解决方案是通过执行
String = randomWord = wordlist[(int)Math.random() * wordlist.length]
或从 wordlist 数组中选择一个随机数
String randomWord = wordlist[(int)Math.random() * 66]