题目
键盘录入学生信息按照总分排序并写入文本文件
分析
录入学生信息,因为需要排序,因此将学生对象存储在 TreeSet 集合中来进行排序;
最后使用高效字符流来打印写入文件中
程序代码
学生类
package com.company.test;
public class Student {
private String name;
private int chineseScore;
private int mathScore;
private int englishScore;
private int totalScore;
public Student() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getChineseScore() {
return chineseScore;
}
public void setChineseScore(int chineseScore) {
this.chineseScore = chineseScore;
}
public int getMathScore() {
return mathScore;
}
public void setMathScore(int mathScore) {
this.mathScore = mathScore;
}
public int getEnglishScore() {
return englishScore;
}
public void setEnglishScore(int englishScore) {
this.englishScore = englishScore;
}
public int getTotalScore() {
return chineseScore+mathScore+englishScore;
}
public void setTotalScore(int totalScore) {
this.totalScore = totalScore;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", chineseScore=" + chineseScore +
", mathScore=" + mathScore +
", englishScore=" + englishScore +
", totalScore=" + totalScore +
'}';
}
}
测试类
package com.company.test;
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 Test {
public static void main(String[] args) throws IOException {
//需要排序,使用 TreeSet集合
TreeSet<Student> set = new TreeSet<>(new Comparator<Student>() {
@Override
public int compare(Student s1, Student s2) {
//比较总分
int num = s2.getTotalScore() - s1.getTotalScore();
//总分相同,比较名字
int num2 = (num == 0) ? s2.getName().compareTo(s1.getName()) : num;
return num2;
}
});
Scanner sc = new Scanner(System.in);
//使用循环来录入学生成绩
for (int i = 1; i < 5; i++) {
System.out.println("开始录入第" + i + "个学生信息------");
System.out.println("请您输入第" + i + "个学生的姓名: ");
String name = sc.nextLine();
System.out.println("请您输入第" + i + "个学生的语文成绩: ");
String chineseScore = sc.nextLine();
System.out.println("请您输入第" + i + "个学生的数学成绩: ");
String mathScore = sc.nextLine();
System.out.println("请您输入第" + i + "个学生的英语成绩: ");
String englishScore = sc.nextLine();
//创建学生对象
Student stu = new Student();
stu.setName(name);
stu.setChineseScore(Integer.parseInt(chineseScore));
stu.setMathScore(Integer.parseInt(mathScore));
stu.setEnglishScore(Integer.parseInt(englishScore));
//添加学生对象
set.add(stu);
}
BufferedWriter bw = new BufferedWriter(new FileWriter("Student.config"));
bw.write("姓名 语文成绩 数学成绩 英语成绩");
bw.newLine();
bw.flush();
for (Student s : set) {
bw.write(s.getName()+" "+s.getChineseScore()+" "+s.getMathScore()+" "+s.getEnglishScore());
bw.newLine();
bw.flush();
}
bw.close();
}
}
运行结果
这个是文件上的内容