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 Student {
private String name;
private int chinese;
private int math;
private int english;
public Student() {
}
public Student(String name, int chinese, int math, int english) {
super();
this.name = name;
this.chinese = chinese;
this.math = math;
this.english = 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;
}
public int getSum() {
return this.chinese + this.math + this.english;
}
}
public class StudentTest {
public static void main(String[] args) throws IOException {
// 写一个学生类,有4个成员变量。
System.out.println("学生信息录入开始");
// 定义TreeSet集合
TreeSet<Student> ts = new TreeSet<Student>(new Comparator<Student>() {
@Override
public int compare(Student s1, Student s2) {
// 主要条件
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.getName().compareTo(s2.getName())
: num3;
return num4;
}
});
for (int x = 0; x < 5; x++) {
// 用Scanner实现键盘录入。
Scanner sc = new Scanner(System.in);
// 键盘录入数据
System.out.println("请输入第" + (x + 1) + "个学生的姓名:");
String name = sc.nextLine();
System.out.println("请输入第" + (x + 1) + "个学生的语文成绩:");
int chinese = sc.nextInt();
System.out.println("请输入第" + (x + 1) + "个学生的数学成绩:");
int math = sc.nextInt();
System.out.println("请输入第" + (x + 1) + "个学生的英语成绩:");
int english = sc.nextInt();
// 把数据封装到学生对象中
Student s = new Student();
s.setName(name);
s.setChinese(chinese);
s.setMath(math);
s.setEnglish(english);
ts.add(s);
}
// 遍历集合,获取到集合中的每一个数据,用输出流写到文本文件。
BufferedWriter bw = new BufferedWriter(new FileWriter("students.txt"));
bw.write("姓名\t语文\t数学\t英语");
bw.newLine();
bw.flush();
for (Student s : ts) {
StringBuilder sb = new StringBuilder();
sb.append(s.getName()).append("\t").append(s.getChinese())
.append("\t").append(s.getMath()).append("\t")
.append(s.getEnglish());
bw.write(sb.toString());
bw.newLine();
bw.flush();
}
bw.close();
System.out.println("学生信息录入成功");
}
}
|