编写一个简单的java图书管理系统
时间: 2024-05-10 19:17:23 浏览: 63
好的,下面是一个简单的Java图书管理系统的代码示例:
```
import java.util.ArrayList;
import java.util.Scanner;
public class BookManagementSystem {
private static ArrayList<Book> books = new ArrayList<Book>();
private static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
while (true) {
System.out.println("请选择操作:");
System.out.println("1. 添加书籍");
System.out.println("2. 删除书籍");
System.out.println("3. 查找书籍");
System.out.println("4. 显示所有书籍");
System.out.println("0. 退出系统");
int choice = scanner.nextInt();
switch (choice) {
case 1:
addBook();
break;
case 2:
deleteBook();
break;
case 3:
findBook();
break;
case 4:
displayBooks();
break;
case 0:
System.out.println("谢谢使用,再见!");
System.exit(0);
default:
System.out.println("输入错误,请重新选择!");
break;
}
}
}
private static void addBook() {
System.out.println("请输入书籍名称:");
String name = scanner.next();
System.out.println("请输入书籍作者:");
String author = scanner.next();
Book book = new Book(name, author);
books.add(book);
System.out.println("添加成功!");
}
private static void deleteBook() {
System.out.println("请输入要删除的书籍名称:");
String name = scanner.next();
boolean flag = false;
for (Book book : books) {
if (book.getName().equals(name)) {
books.remove(book);
flag = true;
System.out.println("删除成功!");
break;
}
}
if (!flag) {
System.out.println("未找到该书籍!");
}
}
private static void findBook() {
System.out.println("请输入要查找的书籍名称:");
String name = scanner.next();
boolean flag = false;
for (Book book : books) {
if (book.getName().equals(name)) {
System.out.println(book);
flag = true;
break;
}
}
if (!flag) {
System.out.println("未找到该书籍!");
}
}
private static void displayBooks() {
if (books.size() == 0) {
System.out.println("暂无书籍!");
} else {
for (Book book : books) {
System.out.println(book);
}
}
}
}
class Book {
private String name;
private String author;
public Book(String name, String author) {
this.name = name;
this.author = author;
}
public String getName() {
return name;
}
public String getAuthor() {
return author;
}
public String toString() {
return "书名:" + name + ",作者:" + author;
}
}
```
这个图书管理系统包含了添加、删除、查找和显示所有书籍等操作,可以根据实际需求进行修改和优化。
阅读全文