-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.java
More file actions
85 lines (75 loc) · 2.65 KB
/
Copy pathmain.java
File metadata and controls
85 lines (75 loc) · 2.65 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
class Student {
private String name;
private List<Double> scores;
public Student(String name, List<Double> scores) {
this.name = name;
this.scores = scores;
}
public String getName() {
return name;
}
public double averageScore() {
if (scores.isEmpty()) {
return 0;
}
double sum = 0;
for (double score : scores) {
sum += score;
}
return sum / scores.size();
}
}
public class StudentReport {
public static List<Student> readStudentsFromCSV(String filePath) {
List<Student> students = new ArrayList<>();
try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
String line;
br.readLine();
while ((line = br.readLine()) != null) {
String[] data = line.split(",");
String name = data[0];
List<Double> scores = new ArrayList<>();
for (int i = 1; i < data.length; i++) {
scores.add(Double.parseDouble(data[i]));
}
students.add(new Student(name, scores));
}
} catch (IOException e) {
System.err.println("Error reading file: " + e.getMessage());
}
return students;
}
public static List<String> generateReport(List<Student> students) {
List<String> reportLines = new ArrayList<>();
reportLines.add("Student Name, Average Score");
for (Student student : students) {
reportLines.add(student.getName() + ", " + String.format("%.2f", student.averageScore()));
}
return reportLines;
}
public static void saveReportToFile(List<String> reportLines, String outputFile) {
try (BufferedWriter bw = new BufferedWriter(new FileWriter(outputFile))) {
for (String line : reportLines) {
bw.write(line);
bw.newLine();
}
System.out.println("Report saved to " + outputFile);
} catch (IOException e) {
System.err.println("Error writing to file: " + e.getMessage());
}
}
public static void main(String[] args) {
String inputFile = "students_scores.csv";
String outputFile = "students_report.csv";
List<Student> students = readStudentsFromCSV(inputFile);
List<String> reportLines = generateReport(students);
saveReportToFile(reportLines, outputFile);
}
}