将学生成绩按照从低到高写入文件中

package com;

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 demo19 {
    //实现学生成绩从高到低排序,写入txt文件中

    public static void main(String[] args) throws IOException {

        TreeSet <Student>treeSet=new TreeSet<>(new Comparator<Student>() {
            @Override
            public int compare(Student o1, Student o2) {
                int num1=o1.sum()-o2.sum();
                int num2=num1==0?o1.getMath()-o2.getMath():num1;
                int num3=num2==0?o1.getChinese()-o2.getChinese():num2;
                return num3;

            }
        });


        for (int i = 0; i <5; i++) {
            Scanner scanner=new Scanner(System.in);
            Student student=new Student();
            System.out.print("请输入学生的姓名:");
            String name = scanner.nextLine();
            student.setName(name);
            System.out.print("请输入学生的数学成绩:");
            int math= scanner.nextInt();
            student.setMath(math);

            System.out.print("请输入学生的语文成绩:");
            int chinese= scanner.nextInt();
            student.setChinese(chinese);
            treeSet.add(student);
        }

        BufferedWriter bw=new BufferedWriter(new FileWriter("E:\\java\\学生成绩.txt"));

        for (Student s:treeSet
             ) {
            //进行字符串拼接
            StringBuilder stringBuilder=new StringBuilder();
            stringBuilder.append(s.getName()).append(":").append("数学成绩").append(s.getMath()).append("语文成绩").append(s.getChinese()).append("总成绩是:").append(s.sum());
            String s1 = stringBuilder.toString();
            bw.write(s1);
            bw.newLine();
            bw.flush();

        }
        bw.close();


    }
}

 Student类

package com;


public class Student {
    private String name;
    private int Math;
    private int Chinese;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getMath() {
        return Math;
    }

    public void setMath(int math) {
        Math = math;
    }

    public int getChinese() {
        return Chinese;
    }

    public void setChinese(int chinese) {
        Chinese = chinese;
    }
    public int sum(){
        return getChinese()+getMath();

    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值