Home › Java Tutorial › Live project: Library books
Live project: Library books
Borrow books using classes and lists.
Use classes, objects, ArrayList and methods to model a small library.
What you will build
- A
Bookclass with a title and an availability flag - A
borrowmethod that searches the shelf - Messages for borrowed, already borrowed and missing books
Steps
- Read the
Bookclass. - Read
borrow: it loops through the shelf. - Press Run and read the messages.
- Add more books and borrow them.
Run it
Press Run to see the project work. Then change the data in the editor and run it again.
Challenge
- Add a
giveBackmethod. - Print all available titles.
Example code
import java.util.ArrayList;
class Main {
static void borrow(ArrayList<Book> shelf, String title) {
for (Book b : shelf) {
if (b.title.equals(title)) {
if (b.available) {
b.available = false;
System.out.println("Borrowed: " + title);
} else {
System.out.println("Already borrowed: " + title);
}
return;
}
}
System.out.println("Not found: " + title);
}
public static void main(String[] args) {
ArrayList<Book> shelf = new ArrayList<>();
shelf.add(new Book("Java Basics"));
shelf.add(new Book("Data Structures"));
borrow(shelf, "Java Basics");
borrow(shelf, "Java Basics");
borrow(shelf, "Algorithms");
int free = 0;
for (Book b : shelf) if (b.available) free++;
System.out.println("Available books: " + free);
}
}
class Book {
String title;
boolean available = true;
Book(String title) { this.title = title; }
}