Java实现图书的借阅功能,通过定义两个类,一个book类,一个library类,通过组合进行书籍的添加
时间: 2023-05-27 11:07:53 浏览: 116
和借阅操作。
Book类:
```
public class Book {
private String title;
private String author;
private String ISBN;
private boolean isBorrowed;
public Book(String title, String author, String ISBN) {
this.title = title;
this.author = author;
this.ISBN = ISBN;
this.isBorrowed = false;
}
public String getTitle() {
return title;
}
public String getAuthor() {
return author;
}
public String getISBN() {
return ISBN;
}
public boolean isBorrowed() {
return isBorrowed;
}
public void setBorrowed(boolean borrowed) {
isBorrowed = borrowed;
}
}
```
Library类:
```
import java.util.ArrayList;
import java.util.List;
public class Library {
private List<Book> books;
public Library() {
books = new ArrayList<>();
}
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()) {
book.setBorrowed(true);
System.out.println("Borrowed book " + book.getTitle() + " by " + book.getAuthor());
} else {
System.out.println("Book " + book.getTitle() + " by " + book.getAuthor() + " is already borrowed");
}
return;
}
}
System.out.println("Book with ISBN " + ISBN + " not found");
}
public void returnBook(String ISBN) {
for (Book book : books) {
if (book.getISBN().equals(ISBN)) {
if (book.isBorrowed()) {
book.setBorrowed(false);
System.out.println("Returned book " + book.getTitle() + " by " + book.getAuthor());
} else {
System.out.println("Book " + book.getTitle() + " by " + book.getAuthor() + " is not borrowed");
}
return;
}
}
System.out.println("Book with ISBN " + ISBN + " not found");
}
}
```
使用示例:
```
Book book1 = new Book("Harry Potter and the Philosopher's Stone", "J.K. Rowling", "9780747532743");
Book book2 = new Book("The Hunger Games", "Suzanne Collins", "9780439023481");
Book book3 = new Book("The Da Vinci Code", "Dan Brown", "9780307474278");
Library library = new Library();
library.addBook(book1);
library.addBook(book2);
library.addBook(book3);
library.borrowBook("9780747532743"); // Borrowed book Harry Potter and the Philosopher's Stone by J.K. Rowling
library.borrowBook("9780747532743"); // Book Harry Potter and the Philosopher's Stone by J.K. Rowling is already borrowed
library.borrowBook("9780439023481"); // Borrowed book The Hunger Games by Suzanne Collins
library.returnBook("9780747532743"); // Returned book Harry Potter and the Philosopher's Stone by J.K. Rowling
library.returnBook("9780307474278"); // Book The Da Vinci Code by Dan Brown is not borrowed
```
输出结果:
```
Borrowed book Harry Potter and the Philosopher's Stone by J.K. Rowling
Book Harry Potter and the Philosopher's Stone by J.K. Rowling is already borrowed
Borrowed book The Hunger Games by Suzanne Collins
Returned book Harry Potter and the Philosopher's Stone by J.K. Rowling
Book The Da Vinci Code by Dan Brown is not borrowed
```