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) {
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;
}
}
class SaveStudent{
public static Scanner sc=new Scanner(System.in);
public static void main(String[] args) throws IOException {
TreeSet<Student> students=new TreeSet(new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
int num=o2.getSum()-o1.getSum();
int num1=num==0?o2.getChinese()-o2.getChinese() : num;
int num2=num1==0?o2.getMath()-o2.getMath():num1;
int num3=num2 == 0 ? o2.getName().compareTo(o1.getName()) : num2;
return num3;
}
});
for (int i = 0; i < 2; i++) {
System.out.println("请输入第"+(i+1)+"个学生的信息:");
System.out.println("请输入学生姓名:");
String name=sc.next();
System.out.println("请输入语文成绩:");
int chinese=sc.nextInt();
System.out.println("请输入数学成绩:");
int math=sc.nextInt();
System.out.println("请输入英语成绩:");
int english=sc.nextInt();
Student student =new Student(name,chinese,math,english);
students.add(student);
}
BufferedWriter bwriter = new BufferedWriter(new FileWriter("C:\\Users\\Administrator\\IdeaProjects\\wwwjava\\day1118\\student.txt"));
//StringBuilder sb = new StringBuilder();//这句为什么放在这里会出现写入的文本混乱?
for (Student student : students) {
//为什么这个要放在for循环里面,而放在外面会写入异常
StringBuilder sb = new StringBuilder();//这句
//为什么这里要用很多的append方法
sb.append(student.getName()+",").append(student.getChinese()+",").append(student.getMath()+",").append(student.getEnglish()+",").append(student.getSum());
bwriter.write(sb.toString());
bwriter.newLine();
bwriter.flush();
}
bwriter.close();
System.out.println("信息录入成功");