用java编写一个图书管理系统
时间: 2023-08-19 21:05:44 浏览: 48
好的,下面是一个简单的图书管理系统的 JAVA 代码示例:
```java
import java.util.ArrayList;
import java.util.Scanner;
class Book {
private int id;
private String title;
private String author;
private boolean available;
public Book(int id, String title, String author, boolean available) {
this.id = id;
this.title = title;
this.author = author;
this.available = available;
}
public int getId() {
return id;
}
public String getTitle() {
return title;
}
public String getAuthor() {
return author;
}
public boolean isAvailable() {
return available;
}
public void setAvailable(boolean available) {
this.available = available;
}
}
class Library {
private ArrayList<Book> books;
public Library(ArrayList<Book> books) {
this.books = books;
}
public ArrayList<Book> getBooks() {
return books;
}
public void setBooks(ArrayList<Book> books) {
this.books = books;
}
public void addBook(Book book) {
books.add(book);
}
public void removeBook(int id) {
for (int i = 0; i < books.size(); i++) {
if (books.get(i).getId() == id) {
books.remove(i);
break;
}
}
}
public void displayBooks() {
System.out.println("ID\tTitle\tAuthor\tAvailable");
for (Book book : books) {
System.out.println(book.getId() + "\t" + book.getTitle() + "\t" + book.getAuthor() + "\t" + book.isAvailable());
}
}
}
public class BookManagementSystem {
public static void main(String[] args) {
ArrayList<Book> books = new ArrayList<>();
books.add(new Book(1, "Java Programming", "John Smith", true));
books.add(new Book(2, "Python Programming", "Jane Doe", false));
books.add(new Book(3, "C++ Programming", "Bob Johnson", true));
Library library = new Library(books);
Scanner scanner = new Scanner(System.in);
int choice;
do {
System.out.println("1. Add book");
System.out.println("2. Remove book");
System.out.println("3. Display books");
System.out.println("0. Exit");
System.out.print("Enter your choice: ");
choice = scanner.nextInt();
switch (choice) {
case 1:
System.out.print("Enter book ID: ");
int id = scanner.nextInt();
scanner.nextLine(); // Consume newline character
System.out.print("Enter book title: ");
String title = scanner.nextLine();
System.out.print("Enter book author: ");
String author = scanner.nextLine();
library.addBook(new Book(id, title, author, true));
break;
case 2:
System.out.print("Enter book ID: ");
id = scanner.nextInt();
library.removeBook(id);
break;
case 3:
library.displayBooks();
break;
case 0:
break;
default:
System.out.println("Invalid choice!");
break;
}
} while (choice != 0);
scanner.close();
}
}
```
该示例包含两个类:`Book` 和 `Library`。`Book` 类表示一本书,包括 ID、标题、作者和可用性等属性。`Library` 类表示一个图书馆,包括一个 `ArrayList` 类型的书籍列表,以及添加、删除和显示书籍的方法。`BookManagementSystem` 类是主类,它创建一个图书馆对象,并提供一个简单的菜单进行添加、删除和显示书籍。