给出该题的Java代码:学生成绩存储在文件中,每行一个学生成绩,形如: 20151201 85 84 91.5 20151202 70 85 65 … 请编程读入学生成绩,并计算各门课程的均值和方差,写入文件的最后一行,如: 均值和方差 71/10 81.2/11.3 76/15.3
时间: 2024-02-05 18:13:51 浏览: 67
学生成绩.java
以下是该题的Java代码:
```java
import java.io.*;
public class StudentGrades {
public static void main(String[] args) {
try {
// 读取文件
BufferedReader br = new BufferedReader(new FileReader("grades.txt"));
// 初始化变量
int count = 0;
double sum1 = 0, sum2 = 0, sum3 = 0;
// 读取每一行并计算各门课程的总成绩
String line;
while ((line = br.readLine()) != null) {
String[] grades = line.split(" ");
sum1 += Double.parseDouble(grades[1]);
sum2 += Double.parseDouble(grades[2]);
sum3 += Double.parseDouble(grades[3]);
count++;
}
// 计算均值和方差
double avg1 = sum1 / count;
double avg2 = sum2 / count;
double avg3 = sum3 / count;
double var1 = 0, var2 = 0, var3 = 0;
br = new BufferedReader(new FileReader("grades.txt"));
while ((line = br.readLine()) != null) {
String[] grades = line.split(" ");
var1 += Math.pow((Double.parseDouble(grades[1]) - avg1), 2);
var2 += Math.pow((Double.parseDouble(grades[2]) - avg2), 2);
var3 += Math.pow((Double.parseDouble(grades[3]) - avg3), 2);
}
var1 /= count;
var2 /= count;
var3 /= count;
// 写入文件
BufferedWriter bw = new BufferedWriter(new FileWriter("grades.txt", true));
bw.write(String.format("\n均值和方差 %.1f/%.1f %.1f/%.1f %.1f/%.1f", avg1, var1, avg2, var2, avg3, var3));
bw.close();
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
假设成绩文件名为`grades.txt`,每行格式为`学号 课程1成绩 课程2成绩 课程3成绩`,如下所示:
```
20151201 85 84 91.5
20151202 70 85 65
20151203 92 88 95
...
```
程序会读取该文件,并计算每门课程的均值和方差,然后将结果写入文件的最后一行。结果格式为`均值和方差 课程1均值/课程1方差 课程2均值/课程2方差 课程3均值/课程3方差`,如下所示:
```
20151201 85 84 91.5
20151202 70 85 65
20151203 92 88 95
...
均值和方差 82.3/67.6 85.7/21.4 83.5/48.2
```
阅读全文