Download as pdf or txt
Download as pdf or txt
You are on page 1of 5

Book class

public class Book {


private String title;
private String author;
private int year;
private boolean isAvailable;

public Book(String title, String author, int year, boolean isAvailable) {


this.title = title;
this.author = author;
this.year = year;
this.isAvailable = isAvailable;
}

public String getTitle() {


return title;
}

public void setTitle(String title) {


this.title = title;
}

public String getAuthor() {


return author;
}

public void setAuthor(String author) {


this.author = author;
}
public int getYear() {
return year;
}

public void setYear(int year) {


this.year = year;
}

public boolean isAvailable() {


return isAvailable;
}

public void setAvailable(boolean available) {


isAvailable = available;
}

public void displayInfo() {


System.out.println("Title: " + title + ", Author: " + author + ", Year: " + year + ",
Available: " + isAvailable);
}
}
Library class
import java.util.ArrayList;

public class Library {


private final ArrayList<Book> books;

public Library() {
books = new ArrayList<>();
}

public void addBook(Book book) {


books.add(book);
}

public void searchByTitle(String title) {


boolean found = false;
for (Book book : books) {
if (book.getTitle().equals(title)) {
found = true;
book.displayInfo();
}
}
if (!found) {
System.out.println("No books found with the title " + title);
}
}

public void checkoutBook(String title) {


for (Book book : books) {
if (book.getTitle().equals(title)) {
if (book.isAvailable()) {
book.setAvailable(false);
System.out.println("Book checked out successfully.");
} else {
System.out.println("Book is not available.");
}
return;
}
}
System.out.println("Book not found.");
}
}
testBook (main method)
public class testBook {
public static void main(String[] args) {
Library library = new Library();

library.addBook(new Book("Upin & Ipin", "Les Copaque", 2007, true));


library.addBook(new Book("Boboiboy", "Monsta", 2010, true));
library.addBook(new Book("Ejen Ali", "Wau", 2020, true));

System.out.println("\nSearching for Ejen Ali:");


library.searchByTitle("Ejen Ali");

System.out.println("\nChecking out Ejen Ali:");


library.checkoutBook("Ejen Ali");

System.out.println("\nChecking out Ejen Ali again:");


library.checkoutBook("Ejen Ali");
}
}

You might also like