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 MyStudentTest {
public static void main(String[] args) throws IOException {
System.out.println("学生信息录入开始");
// 定义TreeSet数组接收学生对象
TreeSet<Student> set = new TreeSet<Student>(new Comparator<Student>() {
public int compare(Student s1, Student s2) {
int num = s2.getSum() - s1.getSum();
int num2 = (num == 0) ? s2.getName().compareTo(s2.getName())
: num;
return num2;
}
});
for (int x = 0; x < 4; 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);
set.add(s);
}
// 遍历Set集合写入到文本文件
BufferedWriter bw = new BufferedWriter(new FileWriter("aaaa.txt"));
bw.write("姓名+\t+语文+\t+数学+\t+英语");
bw.newLine();
bw.flush();
for (Student s : set) {
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(s.toString());
bw.newLine();
bw.flush();
}
bw.close();
System.out.println("学生信息录入成功");
}
}
|
|