Files
oop/finalproject/Question8/Library.java
2022-05-24 23:35:04 +08:00

123 lines
2.8 KiB
Java

/*
* Author: CHEN Yongyuan (Walter) 1930006025 from OOP(1007)
* Date: 2022-04-25
* Description: This is the Library class.
*/
import java.util.ArrayList;
public class Library {
private String name;
private ArrayList<IUser> users;
private ArrayList<ModelListener> listeners;
/**
* Constructor.
*
* @param name
*/
public Library(String name) {
this.name = name;
// init array list
this.users = new ArrayList<IUser>();
this.listeners = new ArrayList<ModelListener>();
}
// GUI Related
public void addListener(ModelListener listener) {
listeners.add(listener);
}
// GUI Related
private void notifyListeners() {
for (ModelListener listener : listeners) {
listener.update();
}
}
/**
* Add the user to the array list.
*
* @param user The user to be added
*/
public void addUser(IUser user) {
users.add(user);
notifyListeners();
}
/**
* The total number of bookds borrowed by all users.
*
* @return the number of books.
*/
public int totalBorrowedBooks() {
int total = 0;
for (IUser user : users) {
total += user.getBook();
}
return total;
}
/**
* Get the number of books borrowed by this user.
*
* @param name the name of the query user
* @return the number of books
* @throws UnknownUserException if user not found
*/
public int getBook(String name) throws UnknownUserException {
for (IUser user : users) {
if (user.getName().equals(name)) {
return user.getBook();
}
}
// user not found
throw new UnknownUserException("User " + name + " unknown.");
}
/**
* Change the number of books currently borrowed by that user.
*
* @param name the user's name
* @param number the number of books
* @throws UnknownUserException user not found
* @throws NotALenderException can not lend book
*/
public void moreBook(String name, int number) throws UnknownUserException, NotALenderException {
for (IUser user : users) {
if (user.getName().equals(name)) {
user.moreBook(number);
notifyListeners();
return;
}
}
// user not found
throw new UnknownUserException("User " + name + " unknown.");
}
/**
* Test.
*/
public static void testLibrary() {
Library li = new Library("UIC Library");
System.out.println(li.totalBorrowedBooks() == 0);
li.addUser(new Lender("L1", 10));
try {
System.out.println(li.getBook("L1") == -10);
System.out.println(li.totalBorrowedBooks() == -10);
li.addUser(new Borrower("B1", 20));
System.out.println(li.getBook("L1") == -10);
System.out.println(li.getBook("B1") == 20);
System.out.println(li.totalBorrowedBooks() == 10);
li.getBook("B2");
} catch (UnknownUserException ex) {
System.out.println(ex.getMessage().equals("User B2 unknown."));
} catch (NotALenderException ex) {
// This should never happen!
System.out.println(false);
}
// More test cases are needed
}
}