用Java实现以下描述,在二进制数据文件STUDENT.DAT中,保存了五个学生的信息(包括学号,姓名,三科成绩,总分),从其中读取数据,输出平均分最高学生的所有信息。...

以下是使用 Java 实现从二进制数据文件 STUDENT.DAT 中读取数据并输出平均分最高学生信息的示例代码:

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;

// 定义学生信息类
class Student {
    public int id;
    public String name;
    public int score1;
    public int score2;
    public int score3;
    public int total;
}

public class Main {
    public static void main(String[] args) {
        // 定义平均分最高的学生
        Student highestAvgStudent = null;

        try (FileInputStream fis = new FileInputStream("STUDENT.DAT");
             BufferedInputStream bis = new BufferedInputStream(fis)) {
            // 循环读取五个学生的信息
            for (int i = 0; i < 5; i++) {
                // 创建学生对象
                Student student = new Student();
                // 从文件中读取学号
                student.id = bis.read();
                // 从文件中读取姓名
                byte[] nameBytes = new byte[20];
                bis.read(nameBytes);
                student.name = new String(nameBytes, "utf-8");
                // 从文件中读取三科成绩
                student.score1 = bis.read();
                student.score2 = bis.read();
                student.score3 = bis.read();
                // 计算总分
                student.total = student.score1 + student.score2 + student.score3;
                // 计算平均分
                double avg = student.total / 3.0;

                // 如果当前学生的平均分高于已有的最高平均分,则更新最高平均分学生信息
                if (highestAvgStudent == null || avg > highestAvgStudent.total / 3.0) {
                    highestAvgStudent = student;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 输出平均分最高的学生信息
        if (highestAvgStudent != null) {
            System.out.println("学号:" + highestAvgStudent.id);
            System.out.println("姓名:" + highestAvgStudent.name);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值