java中学生成绩存储在文件中,每行一个学生成绩,形如: 20151201 85 84 91.5 20151202 70 85 65 … 请编程读入学生成绩,并计算各门课程的均值和方差,写入文件的最后一行,如: 均值和方差 71/10 81.2/11.3 76/15.3
时间: 2024-02-07 07:01:47 浏览: 144
java用list集合存储学生信息并算出成绩平均值操作
5星 · 资源好评率100%
好的,我可以帮你解决这个问题。以下是Java代码示例:
```java
import java.io.*;
public class GradeStatistics {
public static void main(String[] args) {
try {
// 读取文件
BufferedReader reader = new BufferedReader(new FileReader("grades.txt"));
String line;
double sum1 = 0, sum2 = 0, sum3 = 0;
int count = 0;
while ((line = reader.readLine()) != null) {
String[] fields = line.split("\\s+"); // 按空格分割字符串
double grade1 = Double.parseDouble(fields[1]);
double grade2 = Double.parseDouble(fields[2]);
double grade3 = Double.parseDouble(fields[3]);
sum1 += grade1;
sum2 += grade2;
sum3 += grade3;
count++;
}
reader.close();
// 计算均值和方差
double avg1 = sum1 / count;
double avg2 = sum2 / count;
double avg3 = sum3 / count;
double var1 = 0, var2 = 0, var3 = 0;
reader = new BufferedReader(new FileReader("grades.txt"));
while ((line = reader.readLine()) != null) {
String[] fields = line.split("\\s+");
double grade1 = Double.parseDouble(fields[1]);
double grade2 = Double.parseDouble(fields[2]);
double grade3 = Double.parseDouble(fields[3]);
var1 += Math.pow(grade1 - avg1, 2);
var2 += Math.pow(grade2 - avg2, 2);
var3 += Math.pow(grade3 - avg3, 2);
}
reader.close();
var1 /= count;
var2 /= count;
var3 /= count;
// 写入文件
BufferedWriter writer = new BufferedWriter(new FileWriter("grades.txt", true));
writer.write(String.format("均值和方差\t%.1f/%.1f\t%.1f/%.1f\t%.1f/%.1f", avg1, var1, avg2, var2, avg3, var3));
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
这个程序会读取名为 `grades.txt` 的文件,计算各门课程的均值和方差,并将结果写入文件的最后一行。你可以根据实际情况修改文件名和路径。注意,程序假定每行数据的格式都是类似于 `20151201 85 84 91.5` 的,第一列是学生的学号,后面三列是三门课程的成绩。如果你的数据格式有所不同,需要相应地修改代码。
阅读全文