-
Notifications
You must be signed in to change notification settings - Fork 0
/
StudentWriter.java
100 lines (86 loc) · 2.37 KB
/
StudentWriter.java
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
99
100
package ws5;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Arrays;
public class StudentWriter {
private static ArrayList<Student> students;
public static void initializeStudents(ArrayList<Student> students) {
StudentWriter.students = students;
}
private static int getStudentAtId(int stdId) {
int index = -1;
for (int i = 0; i < students.size(); i++) {
Integer x = students.get(i).getStdId();
Integer y = stdId;
if (x.equals(y)) {
index = i;
}
}
return index;
}
public static String writeStudents(String stdId, String firstName, String lastName, String courses) {
ArrayList<String> courseList = new ArrayList<String>(Arrays.asList(courses.split(",")));
String returnMsg = "";
try {
int studentId = Integer.parseInt(stdId);
int index = getStudentAtId(studentId);
if (index == -1) {
Student student = new Student(studentId, firstName, lastName, courseList);
students.add(student);
}
else {
returnMsg = "Student with id:" + stdId + " already exists.";
}
}
catch (NumberFormatException e) {
returnMsg = "Invalid studentId: Must be a whole number with no decimals.";
}
catch (StudentException e) {
returnMsg = e.toString();
}
try {
FileOutputStream fos = new FileOutputStream("students.ser");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(students);
oos.flush();
oos.close();
if (returnMsg.equals("")) {
returnMsg = "Student saved successfully.";
}
}
catch (IOException e) {
returnMsg = e.toString();
}
return returnMsg;
}
public static String deleteStudent(String stdId) {
String returnMsg = "";
try {
int studentId = Integer.parseInt(stdId);
int index = getStudentAtId(studentId);
if (!(index == -1)) {
students.remove(index);
try {
FileOutputStream fos = new FileOutputStream("students.ser");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(students);
oos.flush();
oos.close();
returnMsg = "Student deleted.";
}
catch (IOException e) {
returnMsg = e.toString();
}
}
else {
returnMsg = "Student not found.";
}
}
catch (NumberFormatException e) {
returnMsg = "Invalid studentId: Must be a whole number with no decimals.";
}
return returnMsg;
}
}