主程序块
package Demo1;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Comparator;
import java.util.Scanner;
import java.util.TreeSet;
/*
* 键盘录入学生信息,按照总分从高到低存入文本文件
* 创建学生对象,创建集合对象,TreeSet,键盘遍历学生信息存储到集合,遍历集合,把数据写到文本
*/
public class StudentDemo {
public static void main(String[] args) throws IOException{
//创建集合对象
TreeSet<Student> ts=new TreeSet<Student>(new Comparator<Student>() {
@Override
public int compare(Student s1, Student s2) {
// TODO Auto-generated method stub
int num=s2.getSum()-s1.getSum();
int num2=num==0?s1.getChinese()-s2.getChinese():num;
int num3=num2==0?s1.getMath()-s2.getMath():num2;
int num4=num3==0?s1.getEnglish()-s2.getEnglish():num3;//多余
int num5=num4==0?s1.getName().compareTo(s2.getName()):num4;
return num5;
}
});
for(int x=1;x<=5;x++) {
Scanner sc=new Scanner(System.in);
System.out.println("请输入第"+x+"个的学生信息");
System.out.println("name:");
String name=sc.nextLine();
System.out.println("Chinese grade:");
int Chineseg=sc.nextInt();
System.out.println("Math grade:");
int Mathg=sc.nextInt();
System.out.println("english grade:");
int englishg=sc.nextInt();
//创建学生对象
Student s=new Student();
s.setName(name);
s.setChinese(Chineseg);
s.setEnglish(englishg);
s.setMath(Mathg);
//把学生信息添加到集合
ts.add(s);
}
//遍历集合,把集合写入文件
BufferedWriter bw=new BufferedWriter(new FileWriter("Student.txt"));
bw.write("学生信息如下:");
bw.newLine();
bw.flush();
bw.write("姓名,语文成绩,数学成绩,英语成绩");
bw.newLine();
bw.flush();
for(Student s:ts) {
StringBuilder sb=new StringBuilder();
sb.append(s.getName()).append(",").append(s.getChinese()).append(",").append(s.getMath()).append(",").append(s.getEnglish());
bw.write(sb.toString());
bw.newLine();
bw.flush();
}
bw.close();
System.out.println("学生信息存储完毕。");
}
private static Object append(int chinese) {
// TODO Auto-generated method stub
return null;
}
}
学生类块
package Demo1;
public class Student {
private String name;
private int chinese;
private int math;
private int english;
public Student(String name, int chinese, int math, int english) {
super();
this.name = name;
this.chinese = chinese;
this.math = math;
this.english = english;
}
public Student() {
super();
// TODO Auto-generated constructor stub
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the chinese
*/
public int getChinese() {
return chinese;
}
/**
* @param chinese the chinese to set
*/
public void setChinese(int chinese) {
this.chinese = chinese;
}
/**
* @return the math
*/
public int getMath() {
return math;
}
/**
* @param math the math to set
*/
public void setMath(int math) {
this.math = math;
}
/**
* @return the english
*/
public int getEnglish() {
return english;
}
/**
* @param english the english to set
*/
public void setEnglish(int english) {
this.english = english;
}
public int getSum() {
return this.chinese+this.math+this.english;
}
}