一个简单的图书管理系统通常包含图书的增加、删除、查询和显示等基本功能。
以下是一个用 Java 编写的简单图书管理系统的示例代码。
css
import java.util.ArrayList;
import java.util.Scanner;
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;
}
@Override
public String toString() {
return "Title: " + title + ", Author: " + author;
}
}
class Library {
private ArrayList<Book> books;
public Library() {
this.books = new ArrayList<>();
}
public void addBook(Book book) {
books.add(book);
System.out.println("Book added successfully.");
}
public void removeBook(String title) {
for (Book book : books) {
if (book.getTitle().equalsIgnoreCase(title)) {
books.remove(book);
System.out.println("Book removed successfully.");
return;
}
}
System.out.println("Book not found.");
}
public void displayBooks() {
if (books.isEmpty()) {
System.out.println("No books in the library.");
} else {
System.out.println("Books in the library:");
for (Book book : books) {
System.out.println(book);
}
}
}
public Book findBook(String title) {
for (Book book : books) {
if (book.getTitle().equalsIgnoreCase(title)) {
return book;
}
}
return null;
}
}
public class LibraryManagementSystem {
public static void main(String[] args) {
Library library = new Library();
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("\nLibrary Management System");
System.out.println("1. Add Book");
System.out.println("2. Remove Book");
System.out.println("3. Display Books");
System.out.println("4. Find Book");
System.out.println("5. Exit");
System.out.print("Enter your choice: ");
int choice = scanner.nextInt();
scanner.nextLine(); // Consume newline
switch (choice) {
case 1:
System.out.print("Enter book title: ");
String title = scanner.nextLine();
System.out.print("Enter book author: ");
String author = scanner.nextLine();
Book newBook = new Book(title, author);
library.addBook(newBook);
break;
case 2:
System.out.print("Enter book title to remove: ");
String titleToRemove = scanner.nextLine();
library.removeBook(titleToRemove);
break;
case 3:
library.displayBooks();
break;
case 4:
System.out.print("Enter book title to find: ");
String titleToFind = scanner.nextLine();
Book foundBook = library.findBook(titleToFind);
if (foundBook != null) {
System.out.println("Book found: " + foundBook);
} else {
System.out.println("Book not found.");
}
break;
case 5:
System.out.println("Exiting the program.");
System.exit(0);
default:
System.out.println("Invalid choice. Please enter a valid option.");
}
}
}
}
这个简单的图书管理系统允许用户添加书籍、删除书籍、显示所有书籍以及查找书籍。用户可以通过输入选项的数字来执行相应的操作。这只是一个基本示例,实际的系统可能需要更多功能和更复杂的设计。