项目需求:
要求用户键盘输入学生信息:姓名,语文成绩,数学成绩英语成绩,然后按照总分数从高到底降序排列,存到.txt文件中之后,然后在控制台打印输出
Student类:
public class Student {
private String name;
private int chinese;
private int math;
private int english;
//求总和
public int Sum(){
return (this.chinese+this.math+this.english);
}
public Student(String name, int chinese, int math, int english) {
this.name = name;
this.chinese = chinese;
this.math = math;
this.english = english;
}
public Student() {
super();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getChinese() {
return chinese;
}
public void setChinese(int chinese) {
this.chinese = chinese;
}
public int getMath() {
return math;
}
public void setMath(int math) {
this.math = math;
}
public int getEnglish() {
return english;
}
public void setEnglish(int english) {
this.english = english;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", chinese=" + chinese +
", math=" + math +
", english=" + english +
'}';
}
}
测试类:
import java.io.*;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Scanner;
import java.util.TreeSet;
public class Test {
public static void main(String[] args) {
//创建TreeMap集合,使用比较器判断出最大成绩
TreeSet<Student> set = new TreeSet<>(new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
//高分在前
int sum = o2.Sum() - o1.Sum();
//防止总成绩相同,如果相同,按照名字排序
int sum1 = sum == 0 ? o2.getName().compareTo(o1.getName()) : sum;
return sum1;
}
});
//键盘录入
for (int i = 0; i < 3; i++) {
//输入学生信息
Scanner sc = new Scanner(System.in);
System.out.println("请输入学生的姓名:");
String name = sc.nextLine();
System.out.println("请输入该学生的语文成绩:");
int chinese = sc.nextInt();
System.out.println("请输入该学生的数学成绩:");
int math = sc.nextInt();
System.out.println("请输入该学生的英语成绩:");
int english = sc.nextInt();
//创建学生对象并存储
Student stu = new Student();
stu.setName(name);
stu.setChinese(chinese);
stu.setMath(math);
stu.setEnglish(english);
//存到集合中
set.add(stu);
}
//读写
try (BufferedWriter bw = new BufferedWriter(new FileWriter("D:\\test\\test.txt"));
BufferedReader br = new BufferedReader(new FileReader("D:\\test\\test.txt"));){
for (Student student : set) {
//创建Stringbuilder拼接
StringBuilder sb = new StringBuilder(student.getName()+","+student.getChinese()+","+student.getMath()+","+student.getEnglish());
//写到文件中
bw.write(sb.toString());
//一次写一行
bw.newLine();
bw.flush();
}
//创建集合
ArrayList<Object> list = new ArrayList<>();
System.out.println("姓名 语文 数学 英语");
String len = null;
while ((len = br.readLine())!=null){
//把读取到的文件信息存到集合中
list.add(len);
}
//遍历
for (Object o : list) {
System.out.println(o);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}