案例
*需求:键盘录入5个学生信息(姓名,语文成绩,数学成绩英语成绩)。要求按照成绩总分从高到低写入文本文件
格式:姓名,语文成绩,数学成绩英语成绩 举例:林青霞98,99,100
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 Demo05Scanner {
public static void main(String[] args) throws IOException {
TreeSet<Student> ts = new TreeSet<>(new Comparator<Student>() {
@Override
public int compare(Student st1, Student st2) {
//成绩从高到底
int num = st2.getSum() - st1.getSum();
//次要条件
//语文成绩相同
int num2 = num ==0? st1.getChinese() -st2.getChinese() : num;
//数学成绩相同
int num3 = num2 ==0 ? st1.getMath() - st2.getMath() : num2;
int num4 = num3 == 0 ? st1.getName().compareTo(st2.getName()) : num3;
return num4;
}
});
BufferedWriter bw = new BufferedWriter(new FileWriter("D:\\java\\成绩.txt"));
Scanner sc = new Scanner(System.in);
for (int i = 0; i < 5; i++) {
Student stu = new Student();
System.out.println("请第"+(i + 1)+"次输入姓名:");
String name = sc.next();
stu.setName(name);
System.out.println("请"+(i + 1)+"次输入语文成绩:");
int chinese = sc.nextInt();
stu.setChinese(chinese);
System.out.println("请"+(i + 1)+"次输入数学成绩:");
int match = sc.nextInt();
stu.setMath(match);
System.out.println("请"+(i + 1)+"次输入英语成绩:");
int english = sc.nextInt();
stu.setEnglish(english);
ts.add(stu);
}
for (Student t : ts) {
//格式:姓名,语文成绩,数学成绩,英语成绩
StringBuilder sb = new StringBuilder();
sb.append(t.getName()).append(",").append(t.getChinese()).append(",").append(t.getMath()).append(",").append(t.getEnglish());
bw.write(sb.toString());
bw.newLine();
bw.flush();
}
bw.close(); // 释放资源
}
好贴
好贴