-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCCRMQuick.java
More file actions
316 lines (286 loc) · 15.1 KB
/
CCRMQuick.java
File metadata and controls
316 lines (286 loc) · 15.1 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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
// Save as CCRMQuick.java
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.*;
public class CCRMQuick {
// --------- Interfaces & Exceptions ----------
interface Persistable { String toCSV(); }
static class MaxCreditLimitExceededException extends Exception {
public MaxCreditLimitExceededException(String msg){ super(msg); }
}
// --------- Abstract Person (Abstraction + Inheritance) ----------
static abstract class Person implements Persistable {
protected String id;
protected String fullName;
protected String email;
protected boolean active;
protected LocalDate createdAt;
public Person(String id, String fullName, String email){
this.id = id; this.fullName = fullName; this.email = email;
this.active = true; this.createdAt = LocalDate.now();
}
public abstract String getRole();
@Override public String toString(){
return String.format("%s[id=%s,name=%s,email=%s,active=%s,created=%s]",
getRole(), id, fullName, email, active, createdAt);
}
}
// --------- Student (encapsulation + inner class) ----------
static class Student extends Person {
private String regNo;
private Map<String,Integer> marks = new HashMap<>(); // courseCode -> marks
private Set<String> enrolled = new HashSet<>();
public Student(String id, String fullName, String email, String regNo){
super(id, fullName, email); this.regNo = regNo;
}
// inner class (example)
class ProfilePrinter {
void printSimple(){ System.out.println(fullName + " (" + regNo + ")"); }
}
public void enroll(String courseCode){ enrolled.add(courseCode); }
public void unenroll(String courseCode){ enrolled.remove(courseCode); marks.remove(courseCode); }
public void recordMark(String courseCode, int mark){
if(!enrolled.contains(courseCode)) throw new IllegalStateException("Not enrolled");
marks.put(courseCode, mark);
}
public Set<String> getEnrolled(){ return Collections.unmodifiableSet(enrolled); }
public Map<String,Integer> getMarks(){ return Collections.unmodifiableMap(marks); }
@Override public String getRole(){ return "Student"; }
@Override public String toCSV(){ return String.join(",", id, regNo, fullName, email, Boolean.toString(active), createdAt.toString()); }
public String transcriptString(DataStore ds){
StringBuilder sb = new StringBuilder();
sb.append("Transcript for ").append(fullName).append(" (").append(regNo).append(")\n");
double totalPoints = 0; int totalCredits = 0;
for(String code: enrolled){
Course c = ds.getCourse(code);
if(c==null) continue;
Integer m = marks.get(code);
String grade = (m==null) ? "N/A" : Grade.fromMarks(m).name();
sb.append(String.format("%s | %s | credits=%d | mark=%s | grade=%s\n",
c.getCode(), c.getTitle(), c.getCredits(), (m==null?"-":m), grade));
if(m!=null){
Grade g = Grade.fromMarks(m);
totalPoints += g.getPoints() * c.getCredits();
totalCredits += c.getCredits();
}
}
double gpa = totalCredits==0 ? 0.0 : totalPoints / totalCredits;
sb.append(String.format("GPA: %.2f\n", gpa));
return sb.toString();
}
}
// --------- Course with Builder ----------
static class Course {
private String code; private String title; private int credits;
private String instructor; private Semester semester; private String department;
private Course(Builder b){
this.code = b.code; this.title = b.title; this.credits = b.credits;
this.instructor = b.instructor; this.semester = b.semester; this.department = b.department;
}
public String getCode(){ return code; }
public String getTitle(){ return title; }
public int getCredits(){ return credits; }
public String getInstructor(){ return instructor; }
public String toCSV(){ return String.join(",", code, title, Integer.toString(credits), instructor, semester.name(), department); }
@Override public String toString(){ return String.format("%s: %s (%d) by %s [%s]", code, title, credits, instructor, semester); }
static class Builder {
private String code; private String title; private int credits = 3;
private String instructor = "TBD"; private Semester semester = Semester.FALL; private String department = "General";
Builder code(String code){ this.code = code; return this; }
Builder title(String title){ this.title = title; return this; }
Builder credits(int c){ this.credits = c; return this; }
Builder instructor(String i){ this.instructor = i; return this; }
Builder semester(Semester s){ this.semester = s; return this; }
Builder department(String d){ this.department = d; return this; }
Course build(){ Objects.requireNonNull(code); Objects.requireNonNull(title); return new Course(this); }
}
}
// --------- Enums ----------
enum Semester { SPRING, SUMMER, FALL }
enum Grade {
S(10), A(9), B(8), C(7), D(6), E(5), F(0);
private final int points;
Grade(int p){ this.points = p; }
public int getPoints(){ return points; }
public static Grade fromMarks(int m){
if(m >= 90) return S;
if(m >= 80) return A;
if(m >= 70) return B;
if(m >= 60) return C;
if(m >= 50) return D;
if(m >= 40) return E;
return F;
}
}
// --------- DataStore Singleton ----------
static class DataStore {
private static DataStore instance;
private Map<String, Student> students = new HashMap<>();
private Map<String, Course> courses = new HashMap<>();
private DataStore(){}
public static synchronized DataStore getInstance(){
if(instance == null) instance = new DataStore();
return instance;
}
public void addStudent(Student s){ students.put(s.id, s); }
public void addCourse(Course c){ courses.put(c.getCode(), c); }
public Student getStudent(String id){ return students.get(id); }
public Course getCourse(String code){ return courses.get(code); }
// Streams + lambda
public List<Course> searchCoursesByInstructor(String instructor){
return courses.values().stream()
.filter(c -> c.getInstructor().equalsIgnoreCase(instructor))
.collect(Collectors.toList());
}
// Enrollment with business rule
public void enroll(String studentId, String courseCode) throws MaxCreditLimitExceededException {
Student s = students.get(studentId);
Course c = courses.get(courseCode);
if(s == null || c == null) throw new IllegalArgumentException("Student/Course missing");
int currentCredits = s.getEnrolled().stream()
.mapToInt(code -> {
Course cc = courses.get(code);
return cc == null ? 0 : cc.getCredits();
}).sum();
if(currentCredits + c.getCredits() > 18) throw new MaxCreditLimitExceededException("Max 18 credits exceeded");
s.enroll(courseCode);
}
public void recordMark(String studentId, String courseCode, int marks){
Student s = students.get(studentId);
if(s == null) throw new IllegalArgumentException("Student missing");
s.recordMark(courseCode, marks);
}
public double computeGPA(String studentId){
Student s = students.get(studentId);
if(s == null) return 0;
double totalPoints = 0; int totalCredits = 0;
for(String code : s.getEnrolled()){
Integer m = s.getMarks().get(code);
Course c = courses.get(code);
if(c == null || m == null) continue;
Grade g = Grade.fromMarks(m);
totalPoints += g.getPoints() * c.getCredits(); totalCredits += c.getCredits();
}
return totalCredits == 0 ? 0.0 : totalPoints / totalCredits;
}
// Export all (NIO.2 + Streams)
public void exportAll(Path folder) throws IOException {
Files.createDirectories(folder);
Path studentsFile = folder.resolve("students.csv");
Path coursesFile = folder.resolve("courses.csv");
List<String> sLines = students.values().stream().map(Student::toCSV).collect(Collectors.toList());
List<String> cLines = courses.values().stream().map(Course::toCSV).collect(Collectors.toList());
Files.write(studentsFile, sLines, StandardCharsets.UTF_8);
Files.write(coursesFile, cLines, StandardCharsets.UTF_8);
}
// Backup
public Path backup(Path root) throws IOException {
String stamp = LocalDate.now().format(DateTimeFormatter.ISO_DATE) + "_" + System.currentTimeMillis();
Path target = root.resolve("backup_" + stamp);
Files.createDirectories(target);
exportAll(target);
return target;
}
// Recursive utility
public static long computeSizeRecursive(Path path) throws IOException {
try (Stream<Path> walk = Files.walk(path)) {
return walk.filter(Files::isRegularFile).mapToLong(p -> {
try { return Files.size(p); } catch(IOException e){ return 0L; }
}).sum();
}
}
}
// --------- CLI (menu-driven) ----------
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
DataStore ds = DataStore.getInstance();
// seed sample data
ds.addCourse(new Course.Builder().code("CS101").title("Intro to CS").credits(4).instructor("DrA").semester(Semester.FALL).department("CS").build());
ds.addCourse(new Course.Builder().code("CS102").title("Data Structures").credits(4).instructor("DrB").semester(Semester.FALL).department("CS").build());
ds.addStudent(new Student("s1","Alice","alice@example.com","REG001"));
ds.addStudent(new Student("s2","Bob","bob@example.com","REG002"));
menuLoop:
while(true){
System.out.println("\n=== CCRM Quick MVP ===");
System.out.println("1) Add Student 2) Add Course 3) Enroll 4) Record Mark");
System.out.println("5) Print Transcript 6) Export 7) Backup & Size 8) Search Courses by Instructor");
System.out.println("9) Show Sample Data 0) Exit");
System.out.print("Choice> ");
String c = sc.nextLine().trim();
try {
switch(c){
case "1":
System.out.print("id: "); String id = sc.nextLine().trim();
System.out.print("regNo: "); String reg = sc.nextLine().trim();
System.out.print("name: "); String name = sc.nextLine().trim();
System.out.print("email: "); String email = sc.nextLine().trim();
ds.addStudent(new Student(id, name, email, reg));
System.out.println("Student added.");
break;
case "2":
System.out.print("code: "); String code = sc.nextLine().trim();
System.out.print("title: "); String title = sc.nextLine().trim();
System.out.print("credits (int): "); int cr = Integer.parseInt(sc.nextLine().trim());
System.out.print("instructor: "); String instr = sc.nextLine().trim();
ds.addCourse(new Course.Builder().code(code).title(title).credits(cr).instructor(instr).build());
System.out.println("Course added.");
break;
case "3":
System.out.print("student id: "); String sid = sc.nextLine().trim();
System.out.print("course code: "); String cc = sc.nextLine().trim();
ds.enroll(sid, cc);
System.out.println("Enrolled.");
break;
case "4":
System.out.print("student id: "); String sId = sc.nextLine().trim();
System.out.print("course code: "); String co = sc.nextLine().trim();
System.out.print("marks (0-100): "); int mk = Integer.parseInt(sc.nextLine().trim());
ds.recordMark(sId, co, mk);
System.out.println("Mark recorded.");
break;
case "5":
System.out.print("student id: "); String sid2 = sc.nextLine().trim();
Student st = ds.getStudent(sid2);
if(st==null) System.out.println("Student not found.");
else System.out.println(st.transcriptString(ds));
break;
case "6":
Path out = Paths.get("exports");
ds.exportAll(out);
System.out.println("Exported to " + out.toAbsolutePath());
break;
case "7":
Path broot = Paths.get("backups");
Path created = ds.backup(broot);
System.out.println("Backup created at " + created.toAbsolutePath());
long bytes = DataStore.computeSizeRecursive(created);
System.out.println("Backup size (bytes): " + bytes);
break;
case "8":
System.out.print("instructor name: "); String ii = sc.nextLine().trim();
List<Course> found = ds.searchCoursesByInstructor(ii);
System.out.println("Found:"); found.forEach(System.out::println);
break;
case "9":
System.out.println("Students:"); ds.students.values().forEach(System.out::println);
System.out.println("Courses:"); ds.courses.values().forEach(System.out::println);
break;
case "0":
System.out.println("Exiting...");
break menuLoop;
default:
System.out.println("Invalid choice.");
}
} catch(MaxCreditLimitExceededException mce){
System.out.println("Business rule: " + mce.getMessage());
} catch(Exception ex){
System.out.println("Error: " + ex.getMessage());
}
}
sc.close();
}
}