import java.util.*;
import java.io.*;
class WriteText
{
public static void main(String[] args) throws Exception
{
TreeSet<Student> ts = new TreeSet<Student>(new Comparator<Student>(){
public int compare(Student s1,Student s2)
{
int num = s2.getTotal()-s1.getTotal();
int num2 = (num==0)?s2.getChineseScore()-s1.getChineseScore():num;
int num3 = (num==0)?s2.getMathScore()-s1.getMathScore():num2;
int num4 = (num==0)?s2.getEnglishScore()-s1.getEnglishScore():num3;
return num4;
}
});
Student s1 = new Student("mara",87,95,98);
Student s2 = new Student("kang",86,99,80);
Student s3 = new Student("ju",77,80,81);
Student s4 = new Student("lin",88,99,60);
ts.add(s1);
ts.add(s2);
ts.add(s3);
ts.add(s4);
BufferedWriter bw = new BufferedWriter(new FileWriter("F:\\TestJava\\IO流\\将成绩按顺序写到文本\\student.txt"));
bw.write("姓名\t\t总分\t\t语文成绩\t\t数学成绩\t\t英语成绩");
bw.newLine();
bw.flush();
for(Student s:ts)
{
bw.write(s.getName()+"\t\t"+s.getTotal()+"\t\t"+s.getChineseScore()+"\t\t"+s.getMathScore()+"\t\t"+s.getEnglishScore());
bw.newLine();
bw.flush();
}
System.out.println("已按总分排序写入文本");
}
}
class Student
{
private String name;
private int chineseScore;
private int mathScore;
private int englishScore;
public Student()
{}
public Student(String name,int chineseScore,int mathScore,int englishScore)
{
this.name = name;
this.chineseScore = chineseScore;
this.mathScore = mathScore;
this.englishScore = englishScore;
}
public String getName()
{
return name;
}
public int getChineseScore()
{
return chineseScore;
}
public int getMathScore()
{
return mathScore;
}
public int getEnglishScore()
{
return englishScore;
}
public int getTotal()
{
return chineseScore+mathScore+englishScore;
}
}
|
|