我遇到了从数组中启动随机字的问题。我不确定如何引用arraylist来取得它。有人能为我的getRandomWord课程指明正确的方向吗?谢谢!
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));
}
}
答案 0 :(得分:2)
这对你有所帮助我认为它能够从一个字符串数组中得到一个随机单词
private static String[] names = { "Terminator", "Slicer","Ninja", "cow", "Robot", "littlegirl" };
name = names[(int) (Math.random() * names.length)];
System.out.println(name);