package com;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Comparator;
import java.util.Scanner;
import java.util.TreeSet;
public class demo19 {
//实现学生成绩从高到低排序,写入txt文件中
public static void main(String[] args) throws IOException {
TreeSet <Student>treeSet=new TreeSet<>(new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
int num1=o1.sum()-o2.sum();
int num2=num1==0?o1.getMath()-o2.getMath():num1;
int num3=num2==0?o1.getChinese()-o2.getChinese():num2;
return num3;
}
});
for (int i = 0; i <5; i++) {
Scanner scanner=new Scanner(System.in);
Student student=new Student();
System.out.print("请输入学生的姓名:");
String name = scanner.nextLine();
student.setName(name);
System.out.print("请输入学生的数学成绩:");
int math= scanner.nextInt();
student.setMath(math);
System.out.print("请输入学生的语文成绩:");
int chinese= scanner.nextInt();
student.setChinese(chinese);
treeSet.add(student);
}
BufferedWriter bw=new BufferedWriter(new FileWriter("E:\\java\\学生成绩.txt"));
for (Student s:treeSet
) {
//进行字符串拼接
StringBuilder stringBuilder=new StringBuilder();
stringBuilder.append(s.getName()).append(":").append("数学成绩").append(s.getMath()).append("语文成绩").append(s.getChinese()).append("总成绩是:").append(s.sum());
String s1 = stringBuilder.toString();
bw.write(s1);
bw.newLine();
bw.flush();
}
bw.close();
}
}
Student类
package com;
public class Student {
private String name;
private int Math;
private int Chinese;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getMath() {
return Math;
}
public void setMath(int math) {
Math = math;
}
public int getChinese() {
return Chinese;
}
public void setChinese(int chinese) {
Chinese = chinese;
}
public int sum(){
return getChinese()+getMath();
}
}