-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStudentManager.java
More file actions
98 lines (69 loc) · 2.31 KB
/
StudentManager.java
File metadata and controls
98 lines (69 loc) · 2.31 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
86
87
88
89
90
91
92
93
94
95
96
97
98
import java.util.ArrayList;
import java.io.*;
public class StudentManager{
private ArrayList<Student> students = new ArrayList<>();
public void addStudent(Student student){
students.add(student);
System.out.println("Student added successfully: " + student);
}
public void viewStudents(){
if(students.isEmpty()){
System.out.println("No students found.");
return;
}
for(Student s : students){
System.out.println(s);
}
}
public void searchStudent(int id){
for (Student s: students){
if(s.getId()== id){
System.out.println("Student found: " + s);
return;
}
}
System.out.println("Student with ID " + id + " not found.");
}
public void deleteStudent(int id){
students.removeIf(s -> s.getId() == id);
System.out.println("Student with ID " + id + " deleted successfully.");
}
// Save all students to file
public void saveToFile() {
try {
// FileWriter writes text into file
BufferedWriter writer =
new BufferedWriter(new FileWriter("students.txt"));
// write each student line by line
for (Student s : students) {
writer.write(s.toFileString());
writer.newLine();
}
writer.close();
} catch (IOException e) {
System.out.println("Error saving file.");
}
}
// Load students from file when program starts
public void loadFromFile() {
try {
BufferedReader reader =
new BufferedReader(new FileReader("students.txt"));
String line;
// read file line by line
while ((line = reader.readLine()) != null) {
// split text using comma
String[] data = line.split(",");
int id = Integer.parseInt(data[0]);
String name = data[1];
int age = Integer.parseInt(data[2]);
String course = data[3];
// recreate Student object
students.add(new Student(id, name, age, course));
}
reader.close();
} catch (IOException e) {
System.out.println("No previous data found.");
}
}
}