题目描述
编写一个Java程序,用于管理五个学生的成绩。每个学生有三门课程的成绩,包括学生号、姓名和三门课成绩。程序需要从键盘接收这些数据,然后计算每个学生的平均成绩,并将包括原始数据和计算出的平均分数在内的所有信息存储到磁盘文件 “stud.txt” 中。
解题思路
- 定义学生类:首先定义一个学生类(Student),包含学生号、姓名和三门课程成绩的属性,以及计算平均成绩的方法。
- 数据输入:使用Scanner类从键盘接收用户输入的学生信息。
- 计算平均分:在学生类中定义一个方法来计算平均成绩。
- 文件操作:使用FileWriter和BufferedWriter将学生信息和计算出的平均分写入到磁盘文件 “stud.txt” 中。
- 异常处理:编写代码时要注意异常处理,确保程序稳定运行。
源码答案
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
class Student {
String studentId;
String name;
int score1;
int score2;
int score3;
public Student(String studentId, String name, int score1, int score2, int score3) {
this.studentId = studentId;
this.name = name;
this.score1 = score1;
this.score2 = score2;
this.score3 = score3;
}
public double calculateAverage() {
return (score1 + score2 + score3) / 3.0;
}
}
public class StudentScoreManagement {
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 studentId = scanner.next();
System.out.print("姓名:");
String name = scanner.next();
System.out.print("课程1成绩:");
int score1 = scanner.nextInt();
System.out.print("课程2成绩:");
int score2 = scanner.nextInt();
System.out.print("课程3成绩:");
int score3 = scanner.nextInt();
students[i] = new Student(studentId, name, score1, score2, score3);
}
// 将学生信息和平均分写入文件
try (BufferedWriter writer = new BufferedWriter(new FileWriter("stud.txt"))) {
for (Student student : students) {
double average = student.calculateAverage();
writer.write("学生号:" + student.studentId + ", 姓名:" + student.name + ", 平均分:" + average);
writer.newLine();
}
System.out.println("学生信息及平均分已写入文件 stud.txt");
} catch (IOException e) {
e.printStackTrace();
}
}
}
输出结果
程序将提示用户输入五个学生的信息,包括学生号、姓名和三门课程的成绩。输入完成后,程序将计算每个学生的平均成绩,并将所有学生的原始数据和平均成绩写入到磁盘文件 “stud.txt” 中。控制台将显示“学生信息及平均分已写入文件 stud.txt”,表示写入操作成功完成。