import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
public class Test {
public static void main(String[] args) throws IOException {
/* names.txt内容:
钦逸抒-女-21-1
屈燕妮-女-24-1
阴诗雁-女-25-1
伯荷燕-女-24-1
欧文新-男-20-1
董泽欧-男-18-1
滕星磊-男-18-1
阚晴岚-女-22-1
傅彬远-男-19-1
左花依-女-24-1
*/
//1.把文件中所有的学生信息读取到内存中
ArrayList<Student> list = new ArrayList<>();
BufferedReader br = new BufferedReader(new FileReader("myiotest\\src\\com\\itheima\\myiotest6\\names.txt"));
String line;
while((line = br.readLine()) != null){
String[] arr = line.split("-");
Student stu = new Student(arr[0],arr[1],Integer.parseInt(arr[2]),Double.parseDouble(arr[3]));
list.add(stu);
}
br.close();
//2.计算权重的总和
double weight = 0;
for (Student stu : list) {
weight = weight + stu.getWeight();
}
//3.计算每一个人的实际占比
//[0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1]
double[] arr = new double[list.size()];
int index = 0;
for (Student stu : list) {
arr[index] = stu.getWeight() / weight;
index++;
}
//4.计算每一个人的权重占比范围
for (int i = 1; i < arr.length; i++) {
arr[i] = arr[i] + arr[i - 1];
}
//5.随机抽取
//获取一个0.0~1.0之间的随机数
double number = Math.random();
//判断number在arr中的位置
//二分查找法
//方法回返回: - 插入点 - 1
//获取number这个数据在数组当中的插入点位置
int result = -Arrays.binarySearch(arr, number) - 1;
Student stu = list.get(result);
System.out.println(stu);
//6.修改当前学生的权重
double w = stu.getWeight() / 2;
stu.setWeight(w);
//7.把集合中的数据再次写到文件中
BufferedWriter bw = new BufferedWriter(new FileWriter("myiotest\\src\\com\\itheima\\myiotest6\\names.txt"));
for (Student s : list) {
bw.write(s.toString());
bw.newLine();
}
bw.close();
}
}
public class Student {
private String name;
private String gender;
private int age;
private double weight;
public Student() {
}
public Student(String name, String gender, int age, double weight) {
this.name = name;
this.gender = gender;
this.age = age;
this.weight = weight;
}
/**
* 获取
*
* @return name
*/
public String getName() {
return name;
}
/**
* 设置
*
* @param name
*/
public void setName(String name) {
this.name = name;
}
/**
* 获取
*
* @return gender
*/
public String getGender() {
return gender;
}
/**
* 设置
*
* @param gender
*/
public void setGender(String gender) {
this.gender = gender;
}
/**
* 获取
*
* @return age
*/
public int getAge() {
return age;
}
/**
* 设置
*
* @param age
*/
public void setAge(int age) {
this.age = age;
}
/**
* 获取
*
* @return weight
*/
public double getWeight() {
return weight;
}
/**
* 设置
*
* @param weight
*/
public void setWeight(double weight) {
this.weight = weight;
}
public String toString() {
return name + "-" + gender + "-" + age + "-" + weight;
}
}