使用Java 某学校进行了一次考试,成绩需保存于文件 score.dat。该文件的格式上要求包含两列信息:学号(长整型)、成绩(单精度浮点数)。编与程序,实现信息的录人、保存和显示。 要求: (1)数据录人、保存功能:通过控制台输人若千学生的学号和成绩,將信息保存到文件 score.dat 中。 (2)数据读取、豆示功能:可以从文件 score.dat 中读取学生的学号和成绩,并显示手控制台。
时间: 2024-03-11 19:50:00 浏览: 17
好的,下面是 Java 版本的示例代码:
```java
import java.io.*;
public class Main {
// 定义学生信息类
static class Student {
public long id; // 学号
public float score; // 成绩
}
// 录入学生信息并保存到文件
public static void saveToFile() {
try {
FileOutputStream fos = new FileOutputStream("score.dat");
DataOutputStream dos = new DataOutputStream(fos);
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Please input the number of students: ");
int n = Integer.parseInt(br.readLine());
Student stu = new Student();
for (int i = 0; i < n; i++) {
System.out.print("Please input the id and score of student " + (i+1) + ": ");
String[] inputs = br.readLine().split(" ");
stu.id = Long.parseLong(inputs[0]);
stu.score = Float.parseFloat(inputs[1]);
dos.writeLong(stu.id);
dos.writeFloat(stu.score);
}
dos.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// 从文件中读取学生信息并显示到控制台
public static void readFromFile() {
try {
FileInputStream fis = new FileInputStream("score.dat");
DataInputStream dis = new DataInputStream(fis);
Student stu = new Student();
while (fis.available() > 0) {
stu.id = dis.readLong();
stu.score = dis.readFloat();
System.out.println("Student id: " + stu.id + ", score: " + stu.score);
}
dis.close();
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
saveToFile(); // 录入学生信息并保存到文件
readFromFile(); // 从文件中读取学生信息并显示到控制台
}
}
```
注意事项:
1. 文件名为 score.dat
2. 写入文件时需要使用 DataOutputStream 类
3. 读取文件时需要使用 FileInputStream 类,并判断文件是否还有数据可读。