Java写图书馆借书还书的小系统
时间: 2023-05-21 11:07:04 浏览: 162
感谢您的提问。以下是Java写图书馆借书还书的小系统的示例代码:
```
import java.util.*;
class Book {
private int id;
private String title;
private String author;
private boolean available;
public Book(int id, String title, String author) {
this.id = id;
this.title = title;
this.author = author;
this.available = true;
}
public int getId() {
return id;
}
public String getTitle() {
return title;
}
public String getAuthor() {
return author;
}
public boolean isAvailable() {
return available;
}
public void setAvailable(boolean available) {
this.available = available;
}
public String toString() {
return "Book[" + id + "] - " + title + " by " + author + " (available=" + available + ")";
}
}
class Library {
private List<Book> books = new ArrayList<Book>();
public void addBook(Book book) {
books.add(book);
}
public Book removeBook(int id) {
for (Book book : books) {
if (book.getId() == id && book.isAvailable()) {
book.setAvailable(false);
return book;
}
}
return null;
}
public void returnBook(int id) {
for (Book book : books) {
if (book.getId() == id && !book.isAvailable()) {
book.setAvailable(true);
break;
}
}
}
public List<Book> getBooks() {
return books;
}
public String toString() {
StringBuilder sb = new StringBuilder();
for (Book book : books) {
sb.append(book.toString()).append("\n");
}
return sb.toString();
}
}
public class LibraryApplication {
public static void main(String[] args) {
Library library = new Library();
Book book1 = new Book(1, "Java Programming", "James Gosling");
Book book2 = new Book(2, "Effective Java", "Joshua Bloch");
Book book3 = new Book(3, "Thinking in Java", "Bruce Eckel");
library.addBook(book1);
library.addBook(book2);
library.addBook(book3);
System.out.println("Library catalog:");
System.out.println(library);
Book borrowedBook = library.removeBook(2);
if (borrowedBook != null) {
System.out.println("Borrowed book: " + borrowedBook.getTitle());
System.out.println("Library catalog after borrowing:");
System.out.println(library);
} else {
System.out.println("Book is not available for borrowing.");
}
library.returnBook(2);
System.out.println("Library catalog after returning:");
System.out.println(library);
}
}
```
请注意,这只是一个简单的示例代码,仅用于说明如何实现图书馆借书还书的系统。在实际应用中,您可能需要考虑更多的方面,例如检查图书的借阅期限,生成借阅报告等等。
阅读全文