-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathLibrary.java
More file actions
72 lines (60 loc) · 2.8 KB
/
Library.java
File metadata and controls
72 lines (60 loc) · 2.8 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
import java.util.ArrayList;
public class Library{
// Private member variable to store a list of the books in the Library.
private ArrayList<Book> books;
// Constructor to initialize the ArrayList of books.
public Library() {
this.books = new ArrayList<Book>();
}
// Method to add a book in the Library's collection.
public void addBook(Book book) {
books.add(book);
}
// Method to display all the available (not borrowed) books in the library.
public void displayAvailableBooks(){
// Iterate through the list of books.
for(Book book : books){
// Checking the availability of the book.
if(book.isAvailable()){
// Display the title and author of the available books.
System.out.println(book.getTitle() + " by " + book.getAuthor());
}
}
}
// Method to borrow a book.
public void borrowBook(String title, String author){
// Iterate through the list of books.
for(Book book : books){
// To check if the book's title and author matches the input and if its available.
if(book.getTitle().equalsIgnoreCase(title) && book.getAuthor().equalsIgnoreCase(author) && book.isAvailable()){
if(book.isAvailable()){
// If the book is available, borrow it.
book.borrowBook();
System.out.println("You have successfully borrowed '" + title + "' by " + author + ".");
} else {
System.out.println("Sorry, '" + title + "' by " + author + " is already borrowed.");
}
return; // Exit the method after borrowing.
}
}
// If the book is not found or available display a message.
System.out.println("Sorry, the book is not available!");
}
// Method to return a book.
public void returnBook(String title, String author){
// Iterate through the list of books.
for(Book book : books){
// Check if the book's itle and author mathes to the input and if its currently borrowed.
if(book.getTitle().equalsIgnoreCase(title) && book.getAuthor().equalsIgnoreCase(author) && book.isBorrowed()){
// If the book is borrowed, return it.
if (!book.isAvailable()) {
book.returnBook(); // Mark the book as returned
System.out.println("You have successfully returned '" + title + "' by " + author + ".");
}
return; // Exit the method after returning.
}
}
// If the book was not found pr wasn't borrowed, display a message.
System.out.println("This book wasn't borrowed from the Library!");
}
}