我有一个名为 getWord() 的方法,但我不知道要向其中添加什么才能实际从文本文件中选择一个单词。我的文本文件由 5 个单词组成。打印文档中的所有单词很容易,但是如何在每次运行程序时以不同的方式打印一个单词。我的代码如下。
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();
}
最佳答案
如果您已经有了文本文件中的单词列表,那么您的问题似乎可以归结为如何为要打印的单词的索引选择一个随机数。在Java中有两种方法可以做到这一点(据我所知)。
您可以使用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());
或者您可以使用Math.random()
。 Math.random()
返回 0(含)和 1(不含)之间的 double 值。
List<String> words; // assign stuff to words
int index = (int)(Math.random() * words.size());
关于java - 从文本文档中随机选择一个单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31173570/