学习IO流已经有一段时间了,有些之前的东西都忘了,乘这次顺便复习一些前面的东西,这次的案例是键盘输入学生的信息(名字,数学成绩,语文成绩,英语成绩),然后按总分排序写入文本文件。
Student类
为了方便写入,我重写了toString方法
public class Student {
private String name;
private int math;
private int chinese;
private int english;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getMath() {
return math;
}
public void setMath(int math) {
this.math = math;
}
public int getChinese() {
return chinese;
}
public void setChinese(int chinese) {
this.chinese = chinese;
}
public int getEnglish() {
return english;
}
public void setEnglish(int english) {
this.english = english;
}
@Override
public String toString() {
return name+" "+math+" "+chinese+" "+english;
}
}
测试类,排序采用的是以前学习的Collections工具类,用匿名内部类的方式对引用类型的数组进行排序。
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.*;
public class Test {
public static void main(String[] args) throws IOException {
BufferedWriter bw=new BufferedWriter(new FileWriter("student.txt"));
ArrayList<Student> students=new ArrayList<>();
for(int i=0;i<3;i++){
Scanner scanner=new Scanner(System.in);
Student student=new Student();
System.out.print("请输入姓名:");
String name=scanner.nextLine();
System.out.print("请输入数学成绩:");
int math=scanner.nextInt();
System.out.print("请输入语文成绩:");
int chinese=scanner.nextInt();
System.out.print("请输入英语成绩:");
int english=scanner.nextInt();
student.setName(name);
student.setMath(math);
student.setChinese(chinese);
student.setEnglish(english);
students.add(student);
}
Collections.sort(students, new Comparator<Student>() {
@Override
public int compare(Student s1, Student s2) {
int sum1=s1.getMath()+s1.getChinese()+s1.getEnglish();
int sum2=s2.getMath()+s2.getChinese()+s2.getEnglish();
int result=sum1==sum2?s1.getName().compareTo(s2.getName()):sum1-sum2;
return result;
}
});
for(Student student:students){
bw.write(student.toString());
bw.newLine();
bw.flush();
}
bw.close();
}
}
最后也是成功的写入到文本文件了

本文回顾了如何通过IO流接收用户输入的学生信息(包括姓名和各科成绩),使用Collections工具对学生成绩进行总分排序,并将结果写入文本文件。重点展示了Student类的定制toString方法和匿名内部类排序算法的应用。
3988

被折叠的 条评论
为什么被折叠?



