import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Scanner;
import java.util.TreeSet;
public class Test4 {
public static void main(String[] args) throws IOException {
TreeSet<Student> ts=getSet();
writeFile(ts);
}
public static void writeFile(TreeSet<Student> ts) throws IOException {
BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream("stu.txt"));
for (Student student : ts) {
byte[] b=student.toString().getBytes();
byte[] b1="\r\n".getBytes(); //换行
bos.write(b);
bos.write(b1);
}
bos.close();
}
public static TreeSet<Student> getSet(){
TreeSet<Student> ts=new TreeSet<>();
Scanner sc=new Scanner(System.in);
System.out.println("请输入学生信息:格式为:(name,30,30,30), over结束");
while(sc.hasNext()){
String str=sc.nextLine();
if(str.equals("over")){//判断是否有"over",有就结束输入。
sc.close(); //释放资源
break;
}
String []s=str.split(","); //切割
//将切割后的信息,放入到TreeSet集合中
ts.add(new Student(s[0],Integer.parseInt(s[1]),Integer.parseInt(s[2]),Integer.parseInt(s[3])));
}
return ts;
}
}
class Student implements Comparable<Student>{//实现Comparaable接口,进行比较
private String name;
private int chinese;
private int math;
private int english;
private int sum;
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=chinese+math+english;
}
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 + "]";
}
@Override
public int compareTo(Student s) {//重写Comparable方法,比较总成绩,
//判断是否是Student,不是输出"类型错误",(可以不写)
if(!(s instanceof Student)){
System.out.println("类型错误!");
}
//"s.sum-this.sum" 可以按高到低的成绩排序,反之是低到高
int num=s.sum-this.sum;
//判断成绩是否相等,相等就在判断姓名是否一样
return num==0?this.name.compareTo(s.name) : num;
}
}
|
|