Java还书功能的实现
时间: 2023-08-28 15:35:36 浏览: 44
Java实现还书功能需要涉及以下步骤:
1. 创建一个图书类Book,包含书名、作者、出版社、ISBN号、借阅状态等属性。
```
public class Book {
private String title; // 书名
private String author; // 作者
private String publisher; // 出版社
private String isbn; // ISBN号
private boolean isBorrowed; // 是否借出
// 构造函数
public Book(String title, String author, String publisher, String isbn) {
this.title = title;
this.author = author;
this.publisher = publisher;
this.isbn = isbn;
this.isBorrowed = false; // 初始状态为未借出
}
// getter和setter方法
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getPublisher() {
return publisher;
}
public void setPublisher(String publisher) {
this.publisher = publisher;
}
public String getIsbn() {
return isbn;
}
public void setIsbn(String isbn) {
this.isbn = isbn;
}
public boolean isBorrowed() {
return isBorrowed;
}
public void setBorrowed(boolean borrowed) {
isBorrowed = borrowed;
}
}
```
2. 创建一个图书馆类Library,包含图书列表、借书和还书的方法。
```
import java.util.ArrayList;
public class Library {
private ArrayList<Book> books; // 图书列表
public Library() {
books = new ArrayList<Book>();
}
// 添加图书
public void addBook(Book book) {
books.add(book);
}
// 借书
public void borrowBook(String isbn) {
for (Book book : books) {
if (book.getIsbn().equals(isbn)) {
if (book.isBorrowed()) {
System.out.println("该书已被借出!");
} else {
book.setBorrowed(true);
System.out.println("借书成功!");
}
return;
}
}
System.out.println("没有找到该书!");
}
// 还书
public void returnBook(String isbn) {
for (Book book : books) {
if (book.getIsbn().equals(isbn)) {
book.setBorrowed(false);
System.out.println("还书成功!");
return;
}
}
System.out.println("没有找到该书!");
}
}
```
3. 测试借书和还书的功能。
```
public class TestLibrary {
public static void main(String[] args) {
Library library = new Library();
// 添加图书
library.addBook(new Book("Java编程思想", "Bruce Eckel", "机械工业出版社", "9787111407010"));
library.addBook(new Book("深入理解Java虚拟机", "周志明", "机械工业出版社", "9787111590653"));
library.addBook(new Book("Java核心技术", "Cay S. Horstmann", "机械工业出版社", "9787111577685"));
// 借书和还书
library.borrowBook("9787111407010");
library.borrowBook("9787111407010");
library.returnBook("9787111407010");
}
}
```
输出结果为:
```
借书成功!
该书已被借出!
还书成功!
```