import java.util.ArrayList; import java.util.Scanner; public class LibrarySystem { private static ArrayList<Book> books = new ArrayList<>(); private static Scanner scanner = new Scanner(System.in); public static void main(String[] args) { while (true) { displayMenu(); int choice = scanner.nextInt(); scanner.nextLine(); // Consume the newline character switch (choice) { case 1: addBook(); break; case 2: viewBookList(); break; case 3: searchBook(); break; case 4: System.out.println("Exiting program. Goodbye!"); System.exit(0); default: System.out.println("Invalid choice. Please try again."); } } } private static void displayMenu() { System.out.println("Library System Menu:"); System.out.println("1. Add Book"); System.out.println("2. View Book List"); System.out.println("3. Search for Book"); System.out.println("4. Exit"); System.out.print("Enter your choice: "); } private static void addBook() { System.out.print("Enter book title: "); String title = scanner.nextLine(); System.out.print("Enter author: "); String author = scanner.nextLine(); books.add(new Book(title, author)); System.out.println("Book added successfully!"); } private static void viewBookList() { if (books.isEmpty()) { System.out.println("No books in the library yet."); } else { System.out.println("Book List:"); for (Book book : books) { System.out.println("Title: " + book.getTitle() + ", Author: " + book.getAuthor()); } } } private static void searchBook() { System.out.print("Enter book title to search: "); String searchTitle = scanner.nextLine(); boolean found = false; for (Book book : books) { if (book.getTitle().equalsIgnoreCase(searchTitle)) { System.out.println("Book found: Title: " + book.getTitle() + ", Author: " + book.getAuthor()); found = true; break; } } if (!found) { System.out.println("Book with title '" + searchTitle + "' not found."); } } private static class Book { private String title; private String author; public Book(String title, String author) { this.title = title; this.author = author; } public String getTitle() { return title; } public String getAuthor() { return author; } } }
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter