用java写一个图书管理系统
时间: 2024-01-06 17:03:18 浏览: 33
当然可以!下面是一个简单的示例代码,实现了一个基本的图书管理系统:
```java
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
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;
}
}
class Library {
private List<Book> books;
public Library() {
this.books = new ArrayList<>();
}
public void addBook(Book book) {
books.add(book);
}
public void removeBook(Book book) {
books.remove(book);
}
public void displayBooks() {
System.out.println("Books in the library:");
for (Book book : books) {
System.out.println("Title: " + book.getTitle() + ", Author: " + book.getAuthor());
}
}
}
public class LibraryManagementSystem {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Library library = new Library();
while (true) {
System.out.println("1. Add book");
System.out.println("2. Remove book");
System.out.println("3. Display books");
System.out.println("4. Exit");
System.out.print("Enter your choice: ");
int choice = scanner.nextInt();
switch (choice) {
case 1:
System.out.print("Enter book title: ");
scanner.nextLine(); // consume newline character
String title = scanner.nextLine();
System.out.print("Enter book author: ");
String author = scanner.nextLine();
Book book = new Book(title, author);
library.addBook(book);
System.out.println("Book added successfully!");
break;
case 2:
System.out.print("Enter book title to remove: ");
scanner.nextLine(); // consume newline character
String removeTitle = scanner.nextLine();
boolean bookRemoved = false;
for (Book b : library.getBooks()) {
if (b.getTitle().equals(removeTitle)) {
library.removeBook(b);
bookRemoved = true;
System.out.println("Book removed successfully!");
break;
}
}
if (!bookRemoved) {
System.out.println("Book not found!");
}
break;
case 3:
library.displayBooks();
break;
case 4:
System.out.println("Exiting...");
System.exit(0);
}
System.out.println();
}
}
}
```
这个示例代码实现了一个简单的图书管理系统,用户可以通过控制台进行添加图书、删除图书和显示图书的操作。你可以根据自己的需求进行扩展和修改。希望对你有所帮助!
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)