Java 数组列表中的随机单词
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20358980/
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
Random word from array list
提问by user3062703
I'm having an issue initiating a random word from the array. I'm not sure how to refer to the words arraylist to fetch from it. Can someone put me in the right direction for my getRandomWord class? Thanks!
我在从数组中启动一个随机单词时遇到问题。我不确定如何引用单词 arraylist 来从中获取。有人可以为我的 getRandomWord 课程指明正确的方向吗?谢谢!
A method getRandomWord which takes nothing as input and returns a random String from words. Remember that you can use the Random class to do this.
一个方法 getRandomWord 什么都不作为输入并从单词中返回一个随机字符串。请记住,您可以使用 Random 类来执行此操作。
import java.io.*;
import java.util.*;
import java.util.Random;
public class WordList{
private ArrayList<String> words;
//Construct String from file
public static void constructor(String filename) throws IOException{
ArrayList words = new ArrayList();
BufferedReader read = new BufferedReader(new FileReader("filename"));
String line = read.readLine();
while (line != null){
words.add(line);
//line = reader.readline();
}
}
public static void getRandomWord(){
Random rand = new Random();
String randomWord = words.get(rand.nextInt(words.size));
}
}
回答by answerSeeker
This will help you I think It's able to get a random word from an array of strings
这将帮助你我认为它能够从字符串数组中获取一个随机单词
private static String[] names = { "Terminator", "Slicer","Ninja", "cow", "Robot", "littlegirl" };
name = names[(int) (Math.random() * names.length)];
System.out.println(name);