以下是使用 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);