题目描述:
给定一个含有多人姓名的文件“xxx.txt”,再其中随机抽取三位幸运儿,将三位幸运儿的姓名写入“幸运儿.txt”。
注意:不允许使用乱序后取前三位
实现思路:
1、读取"xxx.txt"中的所有姓名:Files.readAl1Lines(path);
2、随机抽取3个幸运儿(不重复)
3、将3个幸运儿的姓名写入"幸运儿.txt"
方式一:
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.*;
public class Demo07 {
public static void main(String[] args) {
try {
//读取txt文件中的所有姓名
List<String> names = Files.readAllLines(Paths.get("F:\\Apesource-java\\fsqlp\\xxx.txt"));
for(String name : names) {
System.out.println(name);
System.out.println();
}
//随机抽取3个幸运儿
LinkedHashSet<String> luckyer = new LinkedHashSet<String>();
while (luckyer.size() < 3) {
int index = (int) (Math.random() * names.size());
String luckyName = names.get(index);
luckyer.add(luckyName);
}
System.out.println(luckyer);
//将3个幸运儿写入"幸运儿.txt"
Files.write(Paths.get("F:\\Apesource-java\\fsqlp\\幸运儿.txt"),
luckyer,
Charset.forName("UTF-8"),
StandardOpenOption.APPEND );
} catch (IOException e) {
e.printStackTrace();
}
}
}
方式二:
public class Demo08 {
public static void main(String[] args) {
//读取”xxx.txt“中所有的姓名
try {
List<String> nameList = Files.readAllLines(Paths.get("F:\\Apesource-java\\fsqlp\\xxx.txt"));
//随机抽取3个幸运儿(不重复)
HashSet<String> lucky = new HashSet<String>();
Random rand = new Random();
for(;;) {
//产生1个随机下标,并根据下标获取对应的姓名
int randIndex = rand.nextInt(nameList.size());
String luckyer = nameList.get(randIndex);
lucky.add(luckyer);
if(lucky.size() == 3) {
break;
}
}
System.out.println(lucky);
//将3个幸运儿的名字写入”幸运儿.txt“
Files.write(Paths.get("F:\\Apesource-java\\fsqlp\\幸运儿.txt"),
lucky);
} catch (IOException e) {
e.printStackTrace();
}
}
}