java代码(2)编程实现以下功能: 1)从键盘输入姓名、学号、成绩,并保存到文本文档中。重复进行,直到输入空字符串为止。 2)从文件中读取各学生的成绩,并计算所有学生成绩的平均值、最大值和最小值。
时间: 2024-03-25 17:40:28 浏览: 104
以下是实现该功能的 Java 代码:
```java
import java.io.*;
import java.util.ArrayList;
public class StudentGrade {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
ArrayList<Student> students = new ArrayList<>();
// 从键盘输入学生信息并保存到文件中
while (true) {
System.out.print("请输入学生姓名:");
String name = reader.readLine();
if (name.equals("")) break;
System.out.print("请输入学生学号:");
String id = reader.readLine();
System.out.print("请输入学生成绩:");
double grade = Double.parseDouble(reader.readLine());
Student student = new Student(name, id, grade);
students.add(student);
FileWriter writer = new FileWriter("students.txt", true);
writer.write(student.toString() + "\n");
writer.close();
}
// 从文件中读取学生信息并计算平均值、最大值和最小值
FileReader fileReader = new FileReader("students.txt");
BufferedReader bufferedReader = new BufferedReader(fileReader);
double sum = 0;
double max = Double.MIN_VALUE;
double min = Double.MAX_VALUE;
int count = 0;
String line;
while ((line = bufferedReader.readLine()) != null) {
String[] parts = line.split(",");
String name = parts[0];
String id = parts[1];
double grade = Double.parseDouble(parts[2]);
Student student = new Student(name, id, grade);
students.add(student);
sum += grade;
max = Math.max(max, grade);
min = Math.min(min, grade);
count++;
}
double average = sum / count;
System.out.println("学生成绩平均值:" + average);
System.out.println("学生成绩最大值:" + max);
System.out.println("学生成绩最小值:" + min);
bufferedReader.close();
fileReader.close();
}
}
class Student {
private String name;
private String id;
private double grade;
public Student(String name, String id, double grade) {
this.name = name;
this.id = id;
this.grade = grade;
}
public String getName() {
return name;
}
public String getId() {
return id;
}
public double getGrade() {
return grade;
}
@Override
public String toString() {
return name + "," + id + "," + grade;
}
}
```
该代码使用了 `BufferedReader` 和 `FileReader` 读取和写入文件,将输入的学生信息保存到 `ArrayList` 中,并在每次输入后将学生信息写入到文件中。然后从文件中读取学生信息,计算平均值、最大值和最小值,并输出结果。
阅读全文