输入5个学生的信息(包含学号、姓名、3科成绩),统计各学生的总分, // 然后将学生信息和统计结果存入二进制数据文件STUDENT.DAT中
时间: 2024-03-11 21:49:08 浏览: 66
可以使用Java的IO流和序列化来实现将学生信息和统计结果存入二进制数据文件中,以下是示例代码:
```java
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.util.Scanner;
public class Student implements java.io.Serializable {
private static final long serialVersionUID = 1L;
private String id;
private String name;
private int score1;
private int score2;
private int score3;
private int totalScore;
public Student(String id, String name, int score1, int score2, int score3) {
this.id = id;
this.name = name;
this.score1 = score1;
this.score2 = score2;
this.score3 = score3;
this.totalScore = score1 + score2 + score3;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
public int getScore1() {
return score1;
}
public int getScore2() {
return score2;
}
public int getScore3() {
return score3;
}
public int getTotalScore() {
return totalScore;
}
}
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Student[] students = new Student[5];
// 输入学生信息
for (int i = 0; i < 5; i++) {
System.out.println("请输入第" + (i + 1) + "个学生的信息:");
System.out.print("学号:");
String id = scanner.next();
System.out.print("姓名:");
String name = scanner.next();
System.out.print("第一科成绩:");
int score1 = scanner.nextInt();
System.out.print("第二科成绩:");
int score2 = scanner.nextInt();
System.out.print("第三科成绩:");
int score3 = scanner.nextInt();
students[i] = new Student(id, name, score1, score2, score3);
}
// 统计总分
int[] totalScores = new int[5];
for (int i = 0; i < 5; i++) {
totalScores[i] = students[i].getTotalScore();
}
// 将学生信息和统计结果存入二进制数据文件中
try {
FileOutputStream fos = new FileOutputStream("STUDENT.DAT");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(students);
oos.writeObject(totalScores);
oos.close();
fos.close();
System.out.println("学生信息已存入STUDENT.DAT文件中。");
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
该示例代码中,通过定义一个Student类和一个存储学生信息和统计结果的数组,实现了输入5个学生的信息和统计各学生总分的功能。然后,通过使用FileOutputStream和ObjectOutputStream将学生信息和统计结果存入二进制数据文件STUDENT.DAT中。
阅读全文