1
我希望能够从文件中读取20个随机名并将它们放入一个新文件中。我如何去做这件事?遇到文件输出问题
public class Assignment2 {
public static void main(String[] args) throws IOException
{
// Read in the file into a list of strings
BufferedReader reader = new BufferedReader(new FileReader("textfile.txt"));
//BufferedWriter bw = new BufferedWriter(new FileWriter("out.txt"));
List<String> lines = new ArrayList<String>();
String line = reader.readLine();
while(line != null) {
lines.add(line);
line = reader.readLine();
}
// Choose a random one from the list
Random r = new Random();
for (int i = 0; i < 20; i++)
{
int rowNum = r.nextInt(lines.size());
System.out.println(lines.get(rowNum));
}
}
}
谢谢..你谈过我是否需要检查一个数字是否被使用..以及我需要确保没有相同的第一个字母重复的名称。我该如何解决这个问题? – CorDell
获得一个随机数,使用这个数字得到一个名字,检查是否不是一个重复的名字(使用一个使用过的名字集合)。如果它不是重复的名称,请添加到集合中。直到收集到20个元素为止。 – andrucz
但它不能成为第一个字母。如果玛丽已经在列表中,那么马克不能是 – CorDell