以下是使用 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);
这段Java代码展示了如何从二进制数据文件STUDENT.DAT中读取学生信息,包括学号、姓名和三科成绩,并计算平均分。程序会找出平均分最高的学生并输出其详细信息。
,从其中读取数据,输出平均分最高学生的所有信息。...&spm=1001.2101.3001.5002&articleId=129075174&d=1&t=3&u=2b9990b03cd94756a7e7d0b99e7c9157)
4758

被折叠的 条评论
为什么被折叠?



