用Java写一个图书管理系统
时间: 2023-10-04 07:03:30 浏览: 16
好的,下面是一个简单的图书管理系统的 Java 代码示例:
```
import java.util.ArrayList;
import java.util.Scanner;
public class BookManagementSystem {
private ArrayList<Book> bookList;
private Scanner scanner;
public BookManagementSystem() {
bookList = new ArrayList<>();
scanner = new Scanner(System.in);
}
public void run() {
while (true) {
System.out.println("请选择操作:1.添加图书 2.删除图书 3.查找图书 4.显示所有图书 5.退出");
int choice = scanner.nextInt();
switch (choice) {
case 1:
addBook();
break;
case 2:
removeBook();
break;
case 3:
searchBook();
break;
case 4:
displayBooks();
break;
case 5:
return;
default:
System.out.println("无效的操作,请重新选择!");
}
}
}
private void addBook() {
System.out.println("请输入图书信息:");
System.out.print("书名:");
String title = scanner.next();
System.out.print("作者:");
String author = scanner.next();
System.out.print("出版社:");
String publisher = scanner.next();
System.out.print("价格:");
double price = scanner.nextDouble();
Book book = new Book(title, author, publisher, price);
bookList.add(book);
System.out.println("添加成功!");
}
private void removeBook() {
System.out.print("请输入要删除的图书的书名:");
String title = scanner.next();
for (int i = 0; i < bookList.size(); i++) {
Book book = bookList.get(i);
if (book.getTitle().equals(title)) {
bookList.remove(i);
System.out.println("删除成功!");
return;
}
}
System.out.println("没有找到要删除的图书!");
}
private void searchBook() {
System.out.print("请输入要查找的图书的书名:");
String title = scanner.next();
for (int i = 0; i < bookList.size(); i++) {
Book book = bookList.get(i);
if (book.getTitle().equals(title)) {
System.out.println("找到了如下图书:");
System.out.println(book);
return;
}
}
System.out.println("没有找到要查找的图书!");
}
private void displayBooks() {
if (bookList.size() == 0) {
System.out.println("当前没有图书!");
return;
}
System.out.println("当前所有图书如下:");
for (Book book : bookList) {
System.out.println(book);
}
}
public static void main(String[] args) {
BookManagementSystem system = new BookManagementSystem();
system.run();
}
}
class Book {
private String title;
private String author;
private String publisher;
private double price;
public Book(String title, String author, String publisher, double price) {
this.title = title;
this.author = author;
this.publisher = publisher;
this.price = price;
}
public String getTitle() {
return title;
}
public String getAuthor() {
return author;
}
public String getPublisher() {
return publisher;
}
public double getPrice() {
return price;
}
@Override
public String toString() {
return "书名:" + title + " 作者:" + author + " 出版社:" + publisher + " 价格:" + price;
}
}
```
这个图书管理系统实现了添加图书、删除图书、查找图书、显示所有图书等功能。运行程序后,用户可以根据菜单选择相应的操作,进行图书管理。