File size: 2,218 Bytes
0284885 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 | package case_package1;
import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
public class Roll_counter {
public static void main(String[] args) throws IOException {
//1、把文件中所有的学生信息读取到内存中
ArrayList<Student> list = new ArrayList<>();
BufferedReader br = new BufferedReader(new FileReader("/Users/zhaoxiaoyong/Documents/" +
"Java/IO_stream_project/Case_module/src/NameInfos.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 student : list) {
weight += student.getWeight();
}
//3、计算每个人的实际占比
double[] arr = new double[list.size()];
int index = 0;
for (Student stu : list) {
arr[index] = stu.getWeight() / weight;
index++;
}
//System.out.println(Arrays.toString(arr));
//4、计算每一个人的权重占比范围
for (int i = 1; i < arr.length; i++) {
arr[i] += arr[i - 1];
}
//System.out.println(Arrays.toString(arr));
//5、随机抽取
//获取一个 0.0 ~ 1.0 之间的随机数
double number = Math.random();
//判断number在arr中的位置
//二分查找法:方法返回 -插入点-1
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("/Users/zhaoxiaoyong/Documents" +
"/Java/IO_stream_project/Case_module/src/NameInfos.txt"));
for (Student s : list) {
bw.write(s.toString());
bw.newLine();
}
bw.close();
}
}
|