[英]Randomly choose a word from a text document
I have a method called getWord() and I don't know what to add to it to actually choose a word from a text file. 我有一个名为getWord()的方法,但我不知道要从文本文件中实际选择一个单词来添加什么内容。 My text file consists of 5 words.
我的文本文件包含5个字。 Its easy printing all words in document, but how can I print one word differently each time I run the program.
它很容易打印文档中的所有单词,但是每次运行程序时如何以不同的方式打印一个单词。 My code is below.
我的代码如下。
private Scanner file;
private final List<String> words;
public TextFile(){
words = readFile();
}
public String getWord(){
return numOfWords;
}
private List<String> readFile() {
List<String> wordList = new ArrayList<String>();
try {
file = new Scanner(new File("words.txt"));
}
} catch (FileNotFoundException e) {
System.out.println("File Not Found");
} catch (Exception e) {
System.out.println("IOEXCEPTION");
}
return wordList;
}
public static void main(String[] args) {
TextFile file = new TextFile();
}
If you already have a list of the words in the text file, it looks like your question boils down to how to choose a random number for the index of the word to print. 如果文本文件中已经有单词列表,则您的问题似乎归结为如何为打印的单词索引选择随机数。 There are two ways to do this in Java (as far as I know).
在Java中,有两种方法可以做到这一点(据我所知)。
You can use a Random
object. 您可以使用
Random
对象。
List<String> words; // assign stuff to words
Random r = new Random();
//yields random number in the range of 0 to words.size()-1 inclusive
int num = r.nextInt(words.size());
Or you can use Math.random()
. 或者,您可以使用
Math.random()
。 Math.random()
returns a double between 0 (inclusive) and 1 (exclusive). Math.random()
返回介于0(含)和1( Math.random()
之间的双Math.random()
值。
List<String> words; // assign stuff to words
int index = (int)(Math.random() * words.size());
There's also the version where your file is 100GB, but you have a word iterator: 还有一个版本,文件大小为100GB,但是有一个单词迭代器:
Iterator<String> iterator = ...;
long wordNumber = 0;
String word = null;
while (iterator.hasNext()) {
String nextWord = iterator.next();
if (Math.random() < 1.0 / ++wordNumber) {
word = nextWord;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.