package com.heima.demo;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Comparator;
import java.util.TreeSet;
import com.heiam.bean.Student;
public class Test1111 {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
TreeSet<Student> ts = new TreeSet<>(new Comparator<Student>() {
@Override
public int compare(Student s1, Student s2) {
int num = s2.getSum() - s1.getSum(); //总分从高到低
return num == 0 ? 1 : num;
}
});
//4,录入五个学生,所以以集合中的学生个数为判断条件,如果size是小于5就进行存储
BufferedReader bw = new BufferedReader(new FileReader("a.txt")); // 创建输入流对象,关联aaa.txt
String s ;
while ((s = bw.readLine()) != null) { // 将读到的字符赋值给ch
String[] arr = s.split(",");
int chinese = Integer.parseInt(arr[1]);
int math = Integer.parseInt(arr[2]);
int english = Integer.parseInt(arr[3]);
ts.add(new Student(arr[0],chinese, math, english));
}
System.out.println("总分从高到低排序后的学生信息:");
System.out.println("姓名"+ " "+ "语文"+" "+"数学"+" "+"英语"+" "+"总成绩"+" "+"平均成绩");
for (Student s1 : ts) {
System.out.println(s1.toString());
}
}
}
用到的学生类
package com.heiam.bean;
public class Student {
private String name; //姓名
private int chinese; //语文成绩
private int math; //数学成绩
private int english; //英语成绩
private int sum; //总分
private int average;
public Student() {
super();
}
public Student(String name, int chinese, int math, int english) {
super();
this.name = name;
this.chinese = chinese;
this.math = math;
this.english = english;
this.sum = this.chinese + this.math + this.english; //根据学生录入的语文,数学,英语成绩计算出总分
this.average =this.sum/3;
}
// public void setSum(int sum){
// this.sum = sum;
// }
public int getSum() {
return sum;
}
public int getAverage() {
return average;
}
public String toString() {
return name + " " + chinese + " " + math + " " + english + " " + sum + " "+ average;
}
}
|
|