【Java】IO流和集合的应用,读取学生成绩文件并统计总分输出前十名

将score.txt的数据读取到集合中,根据学生学号统计总成绩,对总成绩降序排序后输出前十名

score.txt文件数据:学号,科目,成绩
在这里插入图片描述
代码如下:

package IO;

import java.io.*;
import java.util.*;

public class Test {
    public static void main(String[] args) {
        HashMap<String, Integer> hashMap = new HashMap<>();

        BufferedReader br = null;
        try {
            br = new BufferedReader(new FileReader("JavaSE/src/IO流/stu_data/score.txt"));
            // 读
            String line;
            while ((line = br.readLine()) != null) {
                // 切分行数据
                String[] splits = line.split(",");
				// 对行数据做脏数据判断
                if (splits.length == 3) {
                    // 学号 成绩
                    String id = splits[0];
                    int score = Integer.parseInt(splits[2]);

                    // 如果已经存在这个学号
                    if (hashMap.containsKey(id)) {
                        // 学号,总成绩(相加上个科目成绩)
                        hashMap.put(id, hashMap.get(id) + score);
                    } else {
                        // 学号,成绩
                        hashMap.put(id, score);
                    }
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException ioException) {
            ioException.printStackTrace();
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException ioException) {
                    ioException.printStackTrace();
                }
            }
        }

        // 排序
        ArrayList<Map.Entry<String, Integer>> list = new ArrayList<>(hashMap.entrySet());
        list.sort(new Comparator<Map.Entry<String, Integer>>() {
            @Override
            public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
                return o2.getValue() - o1.getValue(); // 总成绩降序排序
            }
        });

        // 遍历输出前十个
        Iterator<Map.Entry<String, Integer>> iterator = list.iterator();
        for (int i = 0; i < 10; i++) {
            if (iterator.hasNext()) {
                Map.Entry<String, Integer> next = iterator.next();
                System.out.println("学号:" + next.getKey() + "\t总分:" + next.getValue());
            }
        }
    }
}

运行结果如下:
在这里插入图片描述

  • 13
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值