【用java在控制台实现简单的图书管理系统】
下面是一个简单的Java控制台应用程序,用于实现图书管理系统的部分功能。这个例子包括添加图书、列出图书列表以及搜索图书。
import java.util.ArrayList;
import java.util.Scanner;
public class BookManager {
private ArrayList<Book> bookList;
public BookManager() {
bookList = new ArrayList<>();
}
public void addBook(Book book) {
bookList.add(book);
System.out.println("Book added successfully.");
}
public void listBooks() {
if (bookList.isEmpty()) {
System.out.println("No books available.");
return;
}
for (Book book : bookList) {
System.out.println(book);
}
}
public Book searchBook(String title) {
for (Book book : bookList) {
if (book.getTitle().equals(title)) {
return book;
}
}
return null;
}
public static void main(String[] args) {
BookManager bookManager = new BookManager();
Scanner scanner = new Scanner(System.in);
// 添加图书
System.out.println("Enter book details:");
System.out.println("Title: ");
String title = scanner.nextLine();
System.out.println("Author: ");
String author = scanner.nextLine();
Book newBook = new Book(title, author);
bookManager.addBook(newBook);
// 列出所有图书
System.out.println("\nList of books:");
bookManager.listBooks();
// 搜索图书
System.out.println("\nEnter title to search: ");
String searchTitle = scanner.nextLine();
Book foundBook = bookManager.searchBook(searchTitle);
if (foundBook != null) {
System.out.println("Found book: " + foundBook);
} else {
System.out.println("Book not found.");
}
scanner.close();
}
}
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 "Book{" +
"title='" + title + '\'' +
", author='" + author + '\'' +
'}';
}
}
这段代码定义了一个简单的Book
类,以及一个BookManager
类,它管理着一本书的列表。BookManager
有添加图书、列出图书和搜索图书的功能。在main
方法中,我们创建了BookManager
评论已关闭