案例:键盘输入学生信息,写入文本文件

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

学习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();
    }
}

最后也是成功的写入到文本文件了

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值