用java写一个简易的图书管理系统
时间: 2023-09-10 21:15:25 浏览: 92
好的,我可以给您提供一个简单的Java图书管理系统的代码框架,您可以在此基础上进行修改和完善。
```java
import java.util.ArrayList;
import java.util.Scanner;
class Book {
private String title;
private String author;
private int id;
public Book(String title, String author, int id) { // 构造函数
this.title = title;
this.author = author;
this.id = id;
}
public String getTitle() { // 获取书名
return title;
}
public String getAuthor() { // 获取作者
return author;
}
public int getId() { // 获取书籍编号
return id;
}
}
class Library {
private ArrayList<Book> books = new ArrayList<Book>(); // 存储书籍的ArrayList
public void addBook(Book book) { // 添加书籍
books.add(book);
}
public void showBooks() { // 显示所有书籍
for (Book book : books) {
System.out.println("Title: " + book.getTitle());
System.out.println("Author: " + book.getAuthor());
System.out.println("ID: " + book.getId());
System.out.println();
}
}
public Book findBook(int id) { // 根据书籍编号查找书籍
for (Book book : books) {
if (book.getId() == id) {
return book;
}
}
return null;
}
public void removeBook(int id) { // 根据书籍编号删除书籍
for (Book book : books) {
if (book.getId() == id) {
books.remove(book);
return;
}
}
}
}
public class BookManagementSystem {
public static void main(String[] args) {
Library library = new Library(); // 创建一个图书馆对象
Scanner scanner = new Scanner(System.in);
while (true) { // 进入主循环
System.out.println("1. Add book");
System.out.println("2. Show all books");
System.out.println("3. Find book");
System.out.println("4. Remove book");
System.out.println("5. Exit");
System.out.println("Please enter your choice (1-5):");
int choice = scanner.nextInt();
scanner.nextLine(); // 吃掉多余的回车
switch (choice) {
case 1: // 添加书籍
System.out.println("Please enter the book title:");
String title = scanner.nextLine();
System.out.println("Please enter the book author:");
String author = scanner.nextLine();
System.out.println("Please enter the book ID:");
int id = scanner.nextInt();
scanner.nextLine(); // 吃掉多余的回车
Book book = new Book(title, author, id);
library.addBook(book);
break;
case 2: // 显示所有书籍
library.showBooks();
break;
case 3: // 查找书籍
System.out.println("Please enter the book ID:");
id = scanner.nextInt();
scanner.nextLine(); // 吃掉多余的回车
book = library.findBook(id);
if (book != null) {
System.out.println("Title: " + book.getTitle());
System.out.println("Author: " + book.getAuthor());
System.out.println("ID: " + book.getId());
System.out.println();
} else {
System.out.println("Book not found.");
}
break;
case 4: // 删除书籍
System.out.println("Please enter the book ID:");
id = scanner.nextInt();
scanner.nextLine(); // 吃掉多余的回车
library.removeBook(id);
break;
case 5: // 退出
return;
default: // 处理非法输入
System.out.println("Invalid choice.");
}
}
}
}
```
这个简单的图书管理系统可以实现以下功能:
1. 添加书籍
2. 显示所有书籍
3. 根据书籍编号查找书籍
4. 根据书籍编号删除书籍
5. 退出
您可以在此基础上进行修改和完善,比如加入借书、还书等功能。
阅读全文