编程构建一个Student类,并在main函数中创建5个对象(对象信息如输入样例所示),其中每个对象的数据包括学号num、姓名name、年龄age以及数学maths、英语english、语文chinese三门功课的分数,然后求出每个人的平均分数ave,将学号、姓名和平均分数输出到磁盘文件STUD.DAT中,最后从STUD.DAT文件中读出这些数据,并显示在屏幕上。 输入格式: 5个学生的数据(学号、姓名、年龄以及数学、英语、语文三门功课的分数)。 输出格式: 从STUD.DAT文件中读出学号、姓名和平均分数。
时间: 2024-02-23 10:56:23 浏览: 83
以下是编写的代码:
```java
import java.io.*;
class Student {
String num;
String name;
int age;
int maths;
int english;
int chinese;
float ave;
public void average() {
ave = (maths + english + chinese) / 3.0f;
}
}
public class Main {
public static void main(String[] args) throws IOException {
Student[] students = new Student[5];
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new FileWriter("STUD.DAT"));
for (int i = 0; i < 5; i++) {
students[i] = new Student();
String[] info = br.readLine().split(" ");
students[i].num = info[0];
students[i].name = info[1];
students[i].age = Integer.parseInt(info[2]);
students[i].maths = Integer.parseInt(info[3]);
students[i].english = Integer.parseInt(info[4]);
students[i].chinese = Integer.parseInt(info[5]);
students[i].average();
bw.write(students[i].num + " " + students[i].name + " " + students[i].ave + "\n");
}
br.close();
bw.close();
BufferedReader br2 = new BufferedReader(new FileReader("STUD.DAT"));
String line;
while ((line = br2.readLine()) != null) {
String[] info = line.split(" ");
System.out.println("Num: " + info[0] + ", Name: " + info[1] + ", Average: " + info[2]);
}
br2.close();
}
}
```
输入样例(每行表示一个学生的信息):
```
1001 Tom 18 80 90 70
1002 Jerry 17 85 70 90
1003 Mary 19 90 85 80
1004 Bob 16 70 80 90
1005 Alice 18 80 75 85
```
输出样例:
```
Num: 1001, Name: Tom, Average: 80.0
Num: 1002, Name: Jerry, Average: 81.666664
Num: 1003, Name: Mary, Average: 85.0
Num: 1004, Name: Bob, Average: 80.0
Num: 1005, Name: Alice, Average: 80.0
```
阅读全文