用面向对象的思想,实现一个学生到图书馆借书和还书的小系统java
时间: 2023-05-30 08:05:12 浏览: 110
//学生类
public class Student {
private String name;
private int id;
private ArrayList<Book> borrowedBooks;
public Student(String name, int id) {
this.name = name;
this.id = id;
borrowedBooks = new ArrayList<>();
}
public String getName() {
return name;
}
public int getId() {
return id;
}
public ArrayList<Book> getBorrowedBooks() {
return borrowedBooks;
}
public void borrowBook(Library library, Book book) {
if (library.lendBook(book)) {
borrowedBooks.add(book);
System.out.println(name + "借阅了<" + book.getTitle() + ">");
} else {
System.out.println(name + "借阅<" + book.getTitle() + ">失败,该书已被借阅");
}
}
public void returnBook(Library library, Book book) {
if (borrowedBooks.contains(book)) {
borrowedBooks.remove(book);
library.returnBook(book);
System.out.println(name + "归还了<" + book.getTitle() + ">");
} else {
System.out.println(name + "没有借阅过<" + book.getTitle() + ">,无法归还");
}
}
}
//图书馆类
public class Library {
private ArrayList<Book> books;
public Library(ArrayList<Book> books) {
this.books = books;
}
public boolean lendBook(Book book) {
if (books.contains(book)) {
books.remove(book);
return true;
} else {
return false;
}
}
public void returnBook(Book book) {
books.add(book);
}
}
//书籍类
public 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;
}
}
//测试类
public class Test {
public static void main(String[] args) {
ArrayList<Book> books = new ArrayList<>();
books.add(new Book("Java程序设计", "张三"));
books.add(new Book("数据结构与算法", "李四"));
books.add(new Book("操作系统", "王五"));
Library library = new Library(books);
Student student1 = new Student("小明", 1001);
Student student2 = new Student("小红", 1002);
student1.borrowBook(library, books.get(0));
student1.borrowBook(library, books.get(1));
student2.borrowBook(library, books.get(0));
student2.returnBook(library, books.get(0));
}
}
阅读全文