Java实现图书的借阅功能,不包含数据库
时间: 2023-05-27 18:05:22 浏览: 85
实现图书的借阅功能可以采用面向对象编程的思想,定义一个Book类和一个Borrower类。
Book类表示图书,包含图书的基本信息:书名、作者、出版社、ISBN号、价格等。Book类还包含一个borrowed属性,表示该书是否已被借出。
Borrower类表示借书人,包含借书人的基本信息:姓名、学号、借书日期、应还日期等。Borrower类还包含一个books属性,表示该借书人借了哪些书。
下面是Java代码的示例:
```java
class Book {
private String title;
private String author;
private String publisher;
private String isbn;
private double price;
private boolean borrowed;
public Book(String title, String author, String publisher, String isbn, double price) {
this.title = title;
this.author = author;
this.publisher = publisher;
this.isbn = isbn;
this.price = price;
this.borrowed = false;
}
public String getTitle() {
return title;
}
public String getAuthor() {
return author;
}
public String getPublisher() {
return publisher;
}
public String getIsbn() {
return isbn;
}
public double getPrice() {
return price;
}
public boolean isBorrowed() {
return borrowed;
}
public void setBorrowed(boolean borrowed) {
this.borrowed = borrowed;
}
}
class Borrower {
private String name;
private String id;
private String borrowDate;
private String returnDate;
private ArrayList<Book> books;
public Borrower(String name, String id, String borrowDate, String returnDate) {
this.name = name;
this.id = id;
this.borrowDate = borrowDate;
this.returnDate = returnDate;
this.books = new ArrayList<Book>();
}
public String getName() {
return name;
}
public String getId() {
return id;
}
public String getBorrowDate() {
return borrowDate;
}
public String getReturnDate() {
return returnDate;
}
public ArrayList<Book> getBooks() {
return books;
}
public void borrowBook(Book book) {
if (book.isBorrowed()) {
System.out.println("Sorry, this book is already borrowed.");
} else {
book.setBorrowed(true);
books.add(book);
System.out.println("You have successfully borrowed " + book.getTitle());
}
}
public void returnBook(Book book) {
if (!book.isBorrowed()) {
System.out.println("This book is not borrowed.");
} else {
book.setBorrowed(false);
books.remove(book);
System.out.println("You have successfully returned " + book.getTitle());
}
}
}
public class Library {
public static void main(String[] args) {
Book book1 = new Book("Java Programming", "John Doe", "O'Reilly Media", "978-0-596-52068-7", 39.99);
Book book2 = new Book("Python Programming", "Jane Smith", "Wiley", "978-1-118-16770-4", 49.99);
Borrower borrower1 = new Borrower("Tom", "123456", "2021-01-01", "2021-02-01");
Borrower borrower2 = new Borrower("Lucy", "654321", "2021-01-02", "2021-02-02");
borrower1.borrowBook(book1);
borrower1.borrowBook(book2);
borrower2.borrowBook(book1);
borrower1.returnBook(book1);
borrower2.returnBook(book1);
}
}
```
在上面的示例中,我们创建了Book和Borrower两个类,并在Library类中进行了测试。首先创建了两本书和两个借书人,然后借书人1先借了书1和书2,借书人2再借书1。接下来借书人1还了书1,借书人2也还了书1。在借书和还书的过程中,我们对图书的borrowed属性进行了修改,以表示图书的借阅状态。
阅读全文