I have to create a book borrowing system by using data structures arraylist. The system include bookId, bookTitle, bookAuthor and genre. There are booklist.txt that have book information - bookId, bookTitle, bookAuthor, genre
1.The system can search the book that user want to borrow by book id or book Title.
2. Ask if the user want to add another book.
3.Count and display the book information that user borrow and the total of the book.
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
private static ArrayList<Book> books;
private static boolean[] isBorrowed;
public static void readBookFile() {
try (BufferedReader reader = new BufferedReader(new FileReader("booklist.txt"))) {
String line;
books = new ArrayList<>();
while ((line = reader.readLine()) != null) {
String[] data = line.split(",");
books.add(new Book(Integer.parseInt(data[0]), data[1], data[2], data[3]));
}
isBorrowed = new boolean[books.size()];
} catch (Exception e) {
e.printStackTrace();
}
}
public static int getIndexByID(int id) {
for (int i = 0; i < books.size(); i++) {
if (books.get(i).getId() == id) {
return i;
}
}
return -1;
}
public static int getIndexByTitle(String title) {
for (int i = 0; i < books.size(); i++) {
if (books.get(i).getTitle().equals(title)) {
return i;
}
}
return -1;
}
public static void borrowBook(int index, Scanner in) {
if (index != -1) {
System.out.println(books.get(index));
if (!isBorrowed[index]) {
System.out.print("Borrow( Y | N )? ");
if (in.nextLine().equalsIgnoreCase("Y")) {
isBorrowed[index] = true;
}
} else {
System.out.println("The book has already been borrowed.");
}
} else {
System.out.println("Book not found.");
}
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
readBookFile();
do {
System.out.println("1. Find book by ID\n2. Find book by Title");
switch (in.nextLine()) {
case "1":
System.out.print("ID: ");
borrowBook(getIndexByID(Integer.parseInt(in.nextLine())), in);
break;
case "2":
System.out.print("Title: ");
borrowBook(getIndexByTitle(in.nextLine()), in);
break;
}
System.out.print("Add another book( Y | N )? ");
} while (!in.nextLine().equalsIgnoreCase("N"));
int total = 0;
System.out.println("You borrow: ");
for (int i = 0; i < isBorrowed.length; i++) {
if (isBorrowed[i]) {
total++;
System.out.println(books.get(i));
}
}
System.out.println("Total: " + total);
}
}
Comments
Leave a comment