forked from IamBisrutPyne/Java-Programs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStudentLibraryManagementSystem.java
More file actions
507 lines (467 loc) · 17.1 KB
/
StudentLibraryManagementSystem.java
File metadata and controls
507 lines (467 loc) · 17.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
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
import java.io.*;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;
/*
* Student Library Management System
* Single-file Java console application for school practical project.
* Features implemented:
* - Admin login (default admin/admin123)
* - Add / Update books
* - Student registration and login
* - Search books (by name / author / id)
* - Issue book (decrements available quantity)
* - Return book (increments available quantity and calculates fine)
* - View issued books (by admin) and view + calculate fine (by student)
* - Persistence using Java Serialization (books.dat, students.dat)
*
* How to compile
* javac StudentLibraryManagementSystem.java
* java StudentLibraryManagementSystem
*
* Default admin credentials: username=admin password=admin123
* Configurable values: FINE_PER_DAY and DEFAULT_ISSUE_DAYS in Library
*/
public class StudentLibraryManagementSystem {
public static void main(String[] args) {
Library library = Library.loadFromDisk();
library.runConsole();
library.saveToDisk();
System.out.println("Exiting. Data saved.");
}
}
// ---------- Models ----------
class Book implements Serializable {
private static final long serialVersionUID = 1L;
int id;
String title;
String author;
int totalQuantity;
int availableQuantity;
public Book(int id, String title, String author, int qty) {
this.id = id;
this.title = title;
this.author = author;
this.totalQuantity = qty;
this.availableQuantity = qty;
}
public String toString() {
return String.format("ID:%d | %s by %s | total:%d | available:%d", id, title, author, totalQuantity, availableQuantity);
}
}
class IssueRecord implements Serializable {
private static final long serialVersionUID = 1L;
int bookId;
LocalDate issueDate;
LocalDate dueDate;
public IssueRecord(int bookId, LocalDate issueDate, LocalDate dueDate) {
this.bookId = bookId;
this.issueDate = issueDate;
this.dueDate = dueDate;
}
}
class Student implements Serializable {
private static final long serialVersionUID = 1L;
String studentId; // unique
String name;
String password;
// Map bookId -> IssueRecord
Map<Integer, IssueRecord> issued = new HashMap<>();
public Student(String studentId, String name, String password) {
this.studentId = studentId;
this.name = name;
this.password = password;
}
public String toString() {
return String.format("%s (%s)", name, studentId);
}
}
// ---------- Library: core logic and persistence ----------
class Library implements Serializable {
private static final long serialVersionUID = 1L;
Map<Integer, Book> books = new HashMap<>();
Map<String, Student> students = new HashMap<>();
// admin credentials (simple)
String adminUser = "admin";
String adminPass = "admin123";
// configuration
static final int FINE_PER_DAY = 5; // currency units per day
static final int DEFAULT_ISSUE_DAYS = 14; // days allowed
transient Scanner scanner = new Scanner(System.in);
// filenames
static final String BOOKS_FILE = "books.dat";
static final String STUDENTS_FILE = "students.dat";
static final String LIBRARY_FILE = "library.dat";
// ---------- Console UI ----------
public void runConsole() {
System.out.println("Welcome to Student Library Management System");
boolean running = true;
while (running) {
System.out.println("\nMain Menu: 1) Admin Login 2) Student Login/Register 3) Search Books 4) Exit");
System.out.print("Choose option: ");
String ch = scanner.nextLine().trim();
switch (ch) {
case "1":
if (adminLogin()) {
adminMenu();
}
break;
case "2":
studentEntry();
break;
case "3":
searchBooksMenu();
break;
case "4":
running = false;
break;
default:
System.out.println("Invalid option.");
}
}
}
// ---------- Admin ----------
boolean adminLogin() {
System.out.print("Admin username: ");
String u = scanner.nextLine().trim();
System.out.print("Admin password: ");
String p = scanner.nextLine().trim();
if (u.equals(adminUser) && p.equals(adminPass)) {
System.out.println("Admin login successful.");
return true;
}
System.out.println("Wrong admin credentials.");
return false;
}
void adminMenu() {
boolean a = true;
while (a) {
System.out.println("\nAdmin Menu: 1) Add Book 2) Update Book 3) Search Books 4) View Issued Books 5) Logout");
System.out.print("Choose option: ");
String ch = scanner.nextLine().trim();
switch (ch) {
case "1":
addBookConsole();
break;
case "2":
updateBookConsole();
break;
case "3":
searchBooksMenu();
break;
case "4":
viewAllIssuedBooks();
break;
case "5":
a = false;
break;
default:
System.out.println("Invalid option.");
}
}
}
void addBookConsole() {
try {
System.out.print("Enter book ID (integer): ");
int id = Integer.parseInt(scanner.nextLine().trim());
if (books.containsKey(id)) {
System.out.println("Book with that ID already exists.");
return;
}
System.out.print("Enter title: ");
String title = scanner.nextLine();
System.out.print("Enter author: ");
String author = scanner.nextLine();
System.out.print("Enter quantity: ");
int qty = Integer.parseInt(scanner.nextLine().trim());
Book b = new Book(id, title, author, qty);
books.put(id, b);
System.out.println("Book added: " + b);
} catch (NumberFormatException e) {
System.out.println("Invalid number.");
}
}
void updateBookConsole() {
System.out.print("Enter book ID to update: ");
try {
int id = Integer.parseInt(scanner.nextLine().trim());
Book b = books.get(id);
if (b == null) {
System.out.println("Book not found.");
return;
}
System.out.println("Current: " + b);
System.out.print("New title (or press Enter to keep): ");
String t = scanner.nextLine();
if (!t.isEmpty()) {
b.title = t;
}
System.out.print("New author (or press Enter to keep): ");
String a = scanner.nextLine();
if (!a.isEmpty()) {
b.author = a;
}
System.out.print("Adjust total quantity (enter integer, can be negative to reduce): ");
String q = scanner.nextLine();
if (!q.isEmpty()) {
int delta = Integer.parseInt(q.trim());
int newTotal = b.totalQuantity + delta;
if (newTotal < 0) {
newTotal = 0;
}
// adjust available proportionally (naive)
int used = b.totalQuantity - b.availableQuantity;
b.totalQuantity = newTotal;
b.availableQuantity = Math.max(0, newTotal - used);
}
System.out.println("Updated: " + b);
} catch (NumberFormatException e) {
System.out.println("Invalid input.");
}
}
void viewAllIssuedBooks() {
System.out.println("\nIssued Books Report:");
boolean any = false;
for (Student s : students.values()) {
if (!s.issued.isEmpty()) {
any = true;
System.out.println("Student: " + s);
for (IssueRecord r : s.issued.values()) {
Book b = books.get(r.bookId);
System.out.printf(" Book: %s | Issued: %s | Due: %s | Fine(if today): %d\n",
(b == null ? "(deleted book)" : b.title),
r.issueDate.format(DateTimeFormatter.ISO_DATE),
r.dueDate.format(DateTimeFormatter.ISO_DATE),
calculateFine(r.dueDate, LocalDate.now()));
}
}
}
if (!any) {
System.out.println("No issued books currently.");
}
}
// ---------- Student registration / login ----------
void studentEntry() {
System.out.println("\n1) Register 2) Login 3) Back");
System.out.print("Choose: ");
String ch = scanner.nextLine().trim();
switch (ch) {
case "1":
registerStudentConsole();
break;
case "2":
studentLoginConsole();
break;
default:
return;
}
}
void registerStudentConsole() {
System.out.print("Enter student ID (unique): ");
String sid = scanner.nextLine().trim();
if (students.containsKey(sid)) {
System.out.println("Student ID already exists.");
return;
}
System.out.print("Enter name: ");
String name = scanner.nextLine();
System.out.print("Enter password: ");
String pass = scanner.nextLine();
Student s = new Student(sid, name, pass);
students.put(sid, s);
System.out.println("Registered: " + s);
}
void studentLoginConsole() {
System.out.print("Student ID: ");
String sid = scanner.nextLine().trim();
System.out.print("Password: ");
String pass = scanner.nextLine().trim();
Student s = students.get(sid);
if (s == null) {
System.out.println("No such student. Register first.");
return;
}
if (!s.password.equals(pass)) {
System.out.println("Wrong password.");
return;
}
System.out.println("Welcome, " + s.name);
studentMenu(s);
}
void studentMenu(Student s) {
boolean run = true;
while (run) {
System.out.println("\nStudent Menu: 1) Search Books 2) Issue Book 3) Return Book 4) My Issued Books 5) Logout");
System.out.print("Choose: ");
String ch = scanner.nextLine().trim();
switch (ch) {
case "1":
searchBooksMenu();
break;
case "2":
issueBookConsole(s);
break;
case "3":
returnBookConsole(s);
break;
case "4":
viewStudentIssued(s);
break;
case "5":
run = false;
break;
default:
System.out.println("Invalid option.");
}
}
}
// ---------- Search ----------
void searchBooksMenu() {
System.out.println("\nSearch by: 1) ID 2) Title keyword 3) Author keyword 4) Back");
System.out.print("Choose: ");
String ch = scanner.nextLine().trim();
switch (ch) {
case "1":
System.out.print("Enter ID: ");
try {
int id = Integer.parseInt(scanner.nextLine().trim());
Book b = books.get(id);
if (b != null) {
System.out.println(b);
}else {
System.out.println("Not found.");
}
} catch (NumberFormatException e) {
System.out.println("Invalid ID.");
}
break;
case "2":
System.out.print("Enter title keyword: ");
String tk = scanner.nextLine().toLowerCase();
books.values().stream().filter(b -> b.title.toLowerCase().contains(tk)).forEach(System.out::println);
break;
case "3":
System.out.print("Enter author keyword: ");
String ak = scanner.nextLine().toLowerCase();
books.values().stream().filter(b -> b.author.toLowerCase().contains(ak)).forEach(System.out::println);
break;
default:
return;
}
}
// ---------- Issue / Return ----------
void issueBookConsole(Student s) {
System.out.print("Enter book ID to issue: ");
try {
int id = Integer.parseInt(scanner.nextLine().trim());
String res = issueBook(s.studentId, id);
System.out.println(res);
} catch (NumberFormatException e) {
System.out.println("Invalid ID.");
}
}
String issueBook(String studentId, int bookId) {
Student s = students.get(studentId);
if (s == null) {
return "Student not found.";
}
Book b = books.get(bookId);
if (b == null) {
return "Book not found.";
}
if (b.availableQuantity <= 0) {
return "No copies available.";
}
if (s.issued.containsKey(bookId)) {
return "You already have this book issued.";
}
LocalDate issueDate = LocalDate.now();
LocalDate dueDate = issueDate.plusDays(DEFAULT_ISSUE_DAYS);
IssueRecord r = new IssueRecord(bookId, issueDate, dueDate);
s.issued.put(bookId, r);
b.availableQuantity -= 1;
saveToDisk();
return String.format("Issued '%s' to %s. Due on %s.", b.title, s.name, dueDate.format(DateTimeFormatter.ISO_DATE));
}
void returnBookConsole(Student s) {
System.out.print("Enter book ID to return: ");
try {
int id = Integer.parseInt(scanner.nextLine().trim());
String res = returnBook(s.studentId, id);
System.out.println(res);
} catch (NumberFormatException e) {
System.out.println("Invalid ID.");
}
}
String returnBook(String studentId, int bookId) {
Student s = students.get(studentId);
if (s == null) {
return "Student not found.";
}
IssueRecord r = s.issued.get(bookId);
if (r == null) {
return "This book is not issued to you.";
}
Book b = books.get(bookId);
if (b != null) {
b.availableQuantity += 1;
}
long fine = calculateFine(r.dueDate, LocalDate.now());
s.issued.remove(bookId);
saveToDisk();
if (fine > 0) {
return String.format("Returned. Fine due: %d (overdue %d days).", fine, ChronoUnit.DAYS.between(r.dueDate, LocalDate.now()));
}else {
return "Returned on time. No fine.";
}
}
void viewStudentIssued(Student s) {
if (s.issued.isEmpty()) {
System.out.println("You have no issued books.");
return;
}
System.out.println("Your issued books:");
for (IssueRecord r : s.issued.values()) {
Book b = books.get(r.bookId);
long fine = calculateFine(r.dueDate, LocalDate.now());
System.out.printf(" ID:%d | %s | Issued:%s | Due:%s | Fine(if today):%d\n",
r.bookId,
(b == null ? "(deleted book)" : b.title),
r.issueDate.format(DateTimeFormatter.ISO_DATE),
r.dueDate.format(DateTimeFormatter.ISO_DATE),
fine);
}
}
long calculateFine(LocalDate due, LocalDate today) {
if (!today.isAfter(due)) {
return 0L;
}
long days = ChronoUnit.DAYS.between(due, today);
return days * FINE_PER_DAY;
}
// ---------- Persistence ----------
public void saveToDisk() {
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(LIBRARY_FILE))) {
oos.writeObject(this);
} catch (IOException e) {
System.out.println("Failed to save library: " + e.getMessage());
}
}
public static Library loadFromDisk() {
File f = new File(LIBRARY_FILE);
if (!f.exists()) {
System.out.println("No saved data found. Starting new library.");
return new Library();
}
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(f))) {
Library lib = (Library) ois.readObject();
lib.scanner = new Scanner(System.in);
System.out.println("Loaded library data.");
return lib;
} catch (Exception e) {
System.out.println("Failed to load saved data: " + e.getMessage());
return new Library();
}
}
}