随机点名器(读取本地文件)(4种点名方式)
思路:读取本地文件
存入集合
第一种直接随机读取
第二种加权
第三种创一个文件计数
第四种通过编写刷新代码
public class RandomRollCall {
public static void main(String[] args) throws IOException {
//RandomRollCall1();
//RandomRollCall2();
//RandomRollCall3();
RandomRollCall4();
}
private static void RandomRollCall4() throws IOException {
//创建集合存入读取内容
ArrayList<String> list = new ArrayList<>();
//一行一行读取文件信息
BufferedReader br = new BufferedReader(new FileReader("src\\MyUrl\\information.txt"));
String line;
while (true){
//判断文件是否为空
if ((line= br.readLine())!=null){
list.add(line.split("-")[0]);
}else if (list.size()==0){
//为空重新生成
refresh.re();
}else {
break;
}
}
br.close();
Random r =new Random();
int i = r.nextInt(list.size());
System.out.println(list.remove(i));
}
private static void RandomRollCall3() throws IOException {
//读取计数器文件
BufferedReader br = new BufferedReader(new FileReader("src\\MyUrl\\count.txt"));
String line;
line= br.readLine();
br.close();
//计数器文件计数+1
FileWriter fw = new FileWriter("src\\MyUrl\\count.txt");
fw.write(Integer.parseInt(line)+1+"");
fw.close();
//此次若是3的倍数,输出张三
if ((Integer.parseInt(line)+1)%3==0){
System.out.println("张三");
return;
}
RandomRollCall1();
}
private static void RandomRollCall2() throws IOException {
//创建集合存入读取内容
ArrayList<String> nanList = new ArrayList<>();
ArrayList<String> nvList = new ArrayList<>();
//一行一行读取文件信息
BufferedReader br = new BufferedReader(new FileReader("src\\MyUrl\\information.txt"));
String line;
while ((line= br.readLine())!=null){
String[] split = line.split("-");
if (split[1].equals("男")){
nanList.add(split[0]);
}else if (split[1].equals("女")){
nvList.add(split[0]);
}else {
System.out.println(line);
}
/*switch (split[1]){
case "男":
nanList.add(split[0]);
case "女":
nvList.add(split[0]);
default:
System.out.println(line);
}*/
}
br.close();
Random r = new Random();
//加权
if (r.nextInt(10)<3){
System.out.println(nvList.get(r.nextInt(nvList.size())));
}else {
System.out.println(nanList.get(r.nextInt(nanList.size())));
}
//此为测试比率是否为7:3
/*int count1=0;
int count2=0;
for (int i = 0; i < 10000000; i++) {
int j = r.nextInt(10);
if (j<3){
count1++;
}else {
count2++;
}
}
System.out.println(count1+","+count2);*/
}
private static void RandomRollCall1() throws IOException {
//创建集合存入读取内容
ArrayList<String> list = new ArrayList<>();
//一行一行读取文件信息
BufferedReader br = new BufferedReader(new FileReader("src\\MyUrl\\information.txt"));
String line;
while ((line= br.readLine())!=null){
list.add(line.split("-")[0]);
}
br.close();
Random r =new Random();
System.out.println(list.get(r.nextInt(list.size())));
}
}
第四中点名方式中的刷新文件内容在上一篇文章
https://blog.youkuaiyun.com/m0_73856491/article/details/129208291