0% found this document useful (0 votes)
3 views19 pages

Split_20250208_0304

The document outlines a library management system's structure, including interfaces, abstract and concrete classes for users (students and faculty), books, loans, and administrative functionalities. Key components include methods for borrowing and returning books, searching for books, and tracking fines. The system is designed to handle user interactions through a main application interface, allowing staff to manage books and users effectively.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views19 pages

Split_20250208_0304

The document outlines a library management system's structure, including interfaces, abstract and concrete classes for users (students and faculty), books, loans, and administrative functionalities. Key components include methods for borrowing and returning books, searching for books, and tracking fines. The system is designed to handle user interactions through a main application interface, allowing staff to manage books and users effectively.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

Question 2

1. Searchable (Interface)

Purpose: Defines search capability contract


Methods:

• boolean matches(String query) - Checks if item matches search criteria

2. User (Abstract Class)

Purpose: Base class for all library users


Instance Variables:

• private String name

• private String id

• private String contactInfo

Methods:

• abstract void borrowBook(Book book)

• abstract void returnBook(Book book)

• abstract List<Book> getBorrowedBooks()

• boolean matches(String query) (Implements Searchable)

• Getters for name, ID, contact info

3. Student (Concrete Class)

Inherits: User
Purpose: Handles student-specific operations
Additional Variables:

• private String major

• private int maxBooksAllowed = 5

• private List<Book> borrowedBooks


Methods:

• void borrowBook(Book book) (Override)

• void returnBook(Book book) (Override)

• List<Book> getBorrowedBooks() (Override)

4. Faculty (Concrete Class)

Inherits: User
Purpose: Handles faculty-specific operations
Additional Variables:

• private String department

• private int maxBooksAllowed = 10

• private List<Book> borrowedBooks

Methods:

• void borrowBook(Book book) (Override)

• void returnBook(Book book) (Override)

• List<Book> getBorrowedBooks() (Override)

5. Book (Class)

Implements: Searchable
Purpose: Represents book entities
Variables:

• private String title

• private String author

• private String isbn

• private boolean available

Methods:

• boolean matches(String query) (Search implementation)


• Getters/Setters for all fields

• boolean isAvailable()

• void setAvailable(boolean available)

6. Loan (Class)

Purpose: Tracks borrowing transactions


Variables:

• private Book book

• private User user

• private LocalDate dueDate

• private LocalDate returnDate

• private static final double DAILY_FINE = 0.50

Methods:

• double calculateFine() - Computes overdue charges

• Getters/Setters for returnDate and other fields

7. Library (Class)

Purpose: Core system operations


Variables:

• private List<Book> books

• private List<User> users

• private List<Loan> loans

Methods:

• void addBook(Book book)

• void removeBook(Book book)

• List<Book> searchBooks(String query)

• Loan borrowBook(User user, Book book, LocalDate dueDate)


• Loan returnBook(User user, Book book, LocalDate returnDate)

• User findUserById(String userId)

8. Staff (Class)

Purpose: Handles administrative tasks


Variables:

• private Library library

Methods:

• void addBook(Book book)

• void removeBook(Book book)

• void registerUser(User user)

• void removeUser(User user)

9. LibrarySystemApp (Main Class)

Purpose: User interface and program flow


Variables:

• private static Library library

• private static Staff staff

• private static Scanner scanner

Key Methods:

• main() - Entry point

• handleStaffActions() - Staff menu

• handleUserActions() - User menu

• borrowBook(User user) - Borrowing workflow

• returnBook(User user) - Returning workflow

• searchBooks() - Search interface

• viewFines(User user) - Fine display


Java code

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.InputMismatchException;
import java.util.List;
import java.util.Scanner;
import java.util.stream.Collectors;

interface Searchable {
boolean matches(String query);
}

abstract class User implements Searchable {


private String name;
private String id;
private String contactInfo;

public User(String name, String id, String contactInfo) {


this.name = name;
this.id = id;
this.contactInfo = contactInfo;
}

public abstract void borrowBook(Book book);


public abstract void returnBook(Book book);
public abstract List<Book> getBorrowedBooks();

@Override
public boolean matches(String query) {
return name.contains(query) || id.contains(query);
}

// Getters
public String getName() { return name; }
public String getId() { return id; }
public String getContactInfo() { return contactInfo; }
}

class Student extends User {


private String major;
private int maxBooksAllowed = 5;
private List<Book> borrowedBooks = new ArrayList<>();

public Student(String name, String id, String contactInfo, String major) {


super(name, id, contactInfo);
this.major = major;
}

@Override
public void borrowBook(Book book) {
if (borrowedBooks.size() >= maxBooksAllowed) {
throw new IllegalStateException("Borrowing limit reached");
}
borrowedBooks.add(book);
book.setAvailable(false);
}

@Override
public void returnBook(Book book) {
if (!borrowedBooks.remove(book)) {
throw new IllegalArgumentException("Book not borrowed by this user");
}
book.setAvailable(true);
}

@Override
public List<Book> getBorrowedBooks() {
return new ArrayList<>(borrowedBooks);
}
}

class Faculty extends User {


private String department;
private int maxBooksAllowed = 10;
private List<Book> borrowedBooks = new ArrayList<>();

public Faculty(String name, String id, String contactInfo, String department) {


super(name, id, contactInfo);
this.department = department;
}

@Override
public void borrowBook(Book book) {
if (borrowedBooks.size() >= maxBooksAllowed) {
throw new IllegalStateException("Borrowing limit reached");
}
borrowedBooks.add(book);
book.setAvailable(false);
}

@Override
public void returnBook(Book book) {
if (!borrowedBooks.remove(book)) {
throw new IllegalArgumentException("Book not borrowed by this user");
}
book.setAvailable(true);
}

@Override
public List<Book> getBorrowedBooks() {
return new ArrayList<>(borrowedBooks);
}
}

class Book implements Searchable {


private String title;
private String author;
private String isbn;
private boolean available;

public Book(String title, String author, String isbn, boolean available) {


this.title = title;
this.author = author;
this.isbn = isbn;
this.available = available;
}

@Override
public boolean matches(String query) {
return title.contains(query) || author.contains(query) || isbn.contains(query);
}

// Getters & Setters


public boolean isAvailable() { return available; }
public void setAvailable(boolean available) { this.available = available; }
public String getTitle() { return title; }
public String getAuthor() { return author; }
public String getIsbn() { return isbn; }
}

class Loan {
private Book book;
private User user;
private LocalDate dueDate;
private LocalDate returnDate;
private static final double DAILY_FINE = 0.50;

public Loan(Book book, User user, LocalDate dueDate) {


this.book = book;
this.user = user;
this.dueDate = dueDate;
}

public double calculateFine() {


LocalDate actualReturnDate = (returnDate == null) ? LocalDate.now() : returnDate;
if (actualReturnDate.isBefore(dueDate) || actualReturnDate.isEqual(dueDate)) return
0.0;
long daysOverdue = actualReturnDate.toEpochDay() - dueDate.toEpochDay();
return daysOverdue * DAILY_FINE;
}
// Getters & Setters
public void setReturnDate(LocalDate returnDate) { this.returnDate = returnDate; }
public Book getBook() { return book; }
public User getUser() { return user; }
public LocalDate getDueDate() { return dueDate; }
}

class Library {
private List<Book> books = new ArrayList<>();
private List<User> users = new ArrayList<>();
private List<Loan> loans = new ArrayList<>();

public void addBook(Book book) { books.add(book); }


public void removeBook(Book book) { books.remove(book); }
public void addUser(User user) { users.add(user); }
public void removeUser(User user) { users.remove(user); }

public List<Book> searchBooks(String query) {


return books.stream()
.filter(book -> book.matches(query))
.collect(Collectors.toList());
}

public Loan borrowBook(User user, Book book, LocalDate dueDate) {


if (!book.isAvailable()) throw new IllegalArgumentException("Book not available");
Loan loan = new Loan(book, user, dueDate);
loans.add(loan);
user.borrowBook(book);
return loan;
}

public Loan returnBook(User user, Book book, LocalDate returnDate) {


Loan loan = loans.stream()
.filter(l -> l.getBook().equals(book) && l.getUser().equals(user))
.findFirst()
.orElseThrow(() -> new IllegalArgumentException("Loan not found"));
loan.setReturnDate(returnDate);
user.returnBook(book);
return loan;
}

public User findUserById(String userId) {


return users.stream()
.filter(u -> u.getId().equals(userId))
.findFirst()
.orElse(null);
}

public List<Loan> getLoansByUser(User user) {


return loans.stream()
.filter(loan -> loan.getUser().equals(user))
.collect(Collectors.toList());
}
}

public class LibrarySystemApp {


private static Library library = new Library();
private static Staff staff = new Staff(library);
private static Scanner scanner = new Scanner(System.in);

public static void main(String[] args) {


while (true) {
System.out.println("\n=== Library Management System ===");
System.out.println("1. Staff Actions");
System.out.println("2. User Actions");
System.out.println("3. Exit");
System.out.print("Select option: ");

try {
int choice = scanner.nextInt();
scanner.nextLine();

switch (choice) {
case 1:
handleStaffActions();
break;
case 2:
handleUserActions();
break;
case 3:
System.out.println("Exiting system...");
return;
default:
System.out.println("Invalid option!");
}
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
scanner.nextLine();
}
}
}

private static void handleStaffActions() {


while (true) {
System.out.println("\nStaff Menu:");
System.out.println("1. Add Book");
System.out.println("2. Register User");
System.out.println("3. Back to Main");
System.out.print("Select option: ");

try {
int choice = scanner.nextInt();
scanner.nextLine();

switch (choice) {
case 1:
addBook();
break;
case 2:
registerUser();
break;
case 3:
return;
default:
System.out.println("Invalid option!");
}
} catch (InputMismatchException e) {
System.out.println("Invalid input! Please enter a number.");
scanner.nextLine();
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
}

private static void addBook() {


try {
System.out.print("Enter book title: ");
String title = scanner.nextLine();
System.out.print("Enter author: ");
String author = scanner.nextLine();
System.out.print("Enter ISBN: ");
String isbn = scanner.nextLine();

Book book = new Book(title, author, isbn, true);


staff.addBook(book);
System.out.println("Book added successfully!");
} catch (Exception e) {
System.out.println("Error adding book: " + e.getMessage());
}
}

private static void registerUser() {


try {
System.out.print("Enter name: ");
String name = scanner.nextLine();
System.out.print("Enter ID: ");
String id = scanner.nextLine();
System.out.print("Enter contact info: ");
String contact = scanner.nextLine();
System.out.println("Select user type:");
System.out.println("1. Student");
System.out.println("2. Faculty");
int type = scanner.nextInt();
scanner.nextLine();

User newUser;
if (type == 1) {
System.out.print("Enter major: ");
String major = scanner.nextLine();
newUser = new Student(name, id, contact, major);
} else if (type == 2) {
System.out.print("Enter department: ");
String dept = scanner.nextLine();
newUser = new Faculty(name, id, contact, dept);
} else {
System.out.println("Invalid user type!");
return;
}
staff.registerUser(newUser);
System.out.println("User registered successfully!");
} catch (Exception e) {
System.out.println("Error registering user: " + e.getMessage());
}
}

private static void handleUserActions() {


try {
System.out.print("\nEnter your user ID: ");
String userId = scanner.nextLine();
User user = library.findUserById(userId);

if (user == null) {
System.out.println("User not found!");
return;
}

while (true) {
System.out.println("\nUser Menu:");
System.out.println("1. Borrow Book");
System.out.println("2. Return Book");
System.out.println("3. Search Books");
System.out.println("4. View Fines");
System.out.println("5. Back to Main");
System.out.print("Select option: ");

int choice = scanner.nextInt();


scanner.nextLine();

switch (choice) {
case 1:
borrowBook(user);
break;
case 2:
returnBook(user);
break;
case 3:
searchBooks();
break;
case 4:
viewFines(user);
break;
case 5:
return;
default:
System.out.println("Invalid option!");
}
}
} catch (InputMismatchException e) {
System.out.println("Invalid input! Please enter a number.");
scanner.nextLine();
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
private static void borrowBook(User user) {
try {
System.out.print("Enter search query (title/author/ISBN): ");
String query = scanner.nextLine();
List<Book> availableBooks = library.searchBooks(query).stream()
.filter(Book::isAvailable)
.collect(Collectors.toList());

Book selectedBook = selectBook(availableBooks);


if (selectedBook == null) return;

LocalDate dueDate = LocalDate.now().plusDays(user instanceof Student ? 14 : 30);


library.borrowBook(user, selectedBook, dueDate);
System.out.println("Book borrowed successfully! Due date: " + dueDate);
} catch (IllegalStateException e) {
System.out.println("Borrowing failed: " + e.getMessage());
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}

private static void returnBook(User user) {


try {
List<Book> borrowedBooks = user.getBorrowedBooks();
if (borrowedBooks.isEmpty()) {
System.out.println("You have no books to return.");
return;
}

Book selectedBook = selectBook(borrowedBooks);


if (selectedBook == null) return;

Loan loan = library.returnBook(user, selectedBook, LocalDate.now());


double fine = loan.calculateFine();
if (fine > 0) {
System.out.printf("Book returned late! Fine: $%.2f%n", fine);
} else {
System.out.println("Book returned successfully!");
}
} catch (Exception e) {
System.out.println("Return failed: " + e.getMessage());
}
}

private static void searchBooks() {


try {
System.out.print("Enter search query (title/author/ISBN): ");
String query = scanner.nextLine();
List<Book> results = library.searchBooks(query);

if (results.isEmpty()) {
System.out.println("No books found.");
return;
}

System.out.println("\nSearch Results:");
results.forEach(book -> System.out.printf(
"- %s by %s (ISBN: %s) %s%n",
book.getTitle(),
book.getAuthor(),
book.getIsbn(),
book.isAvailable() ? "[Available]" : "[Borrowed]"
));
} catch (Exception e) {
System.out.println("Search error: " + e.getMessage());
}
}

private static void viewFines(User user) {


List<Loan> userLoans = library.getLoansByUser(user);
double totalFine = 0.0;

System.out.println("\nCurrent Fines:");
for (Loan loan : userLoans) {
double fine = loan.calculateFine();
if (fine > 0) {
System.out.printf("- %s: Due %s, Fine $%.2f%n",
loan.getBook().getTitle(),
loan.getDueDate(),
fine
);
totalFine += fine;
}
}
System.out.printf("Total fines due: $%.2f%n", totalFine);
}

private static Book selectBook(List<Book> books) {


try {
if (books.isEmpty()) {
System.out.println("No books found!");
return null;
}

System.out.println("\nSelect a book:");
for (int i = 0; i < books.size(); i++) {
Book book = books.get(i);
System.out.printf("%d. %s by %s [%s]%n",
i + 1,
book.getTitle(),
book.getAuthor(),
book.isAvailable() ? "Available" : "Borrowed");
}

System.out.print("Enter book number (0 to cancel): ");


int choice = scanner.nextInt();
scanner.nextLine();

if (choice == 0) return null;


if (choice < 1 || choice > books.size()) {
System.out.println("Invalid selection!");
return null;
}
return books.get(choice - 1);
} catch (InputMismatchException e) {
System.out.println("Invalid input! Please enter a number.");
scanner.nextLine();
return null;
}
}
}

class Staff {
private Library library;

public Staff(Library library) { this.library = library; }


public void addBook(Book book) { library.addBook(book); }
public void removeBook(Book book) { library.removeBook(book); }
public void registerUser(User user) { library.addUser(user); }
public void removeUser(User user) { library.removeUser(user); }
}

output

if we select option one the out put looks like

You might also like