【笔记】Eclipse and Java for Total Beginners—014

Lesson 14 – Finish checkOut Method

  • Write getBooksForPerson method
  • Introduce for each loop
  • Introduce logical ‘and’ operator &&
  • NullPointerException errors
  • Complete checkOut Method

1 package org.totalbeginner.tutorial;
2
3  import java.util.ArrayList;
4
5  import org.totoalbeginner.tutorial.Person;
6
7  public class MyLibrary {
8
9 String name;
10 public String getName() {
11 return name;
12 }
13
14 public ArrayList<Person> getPeople() {
15 return people;
16 }
17
18 public ArrayList<Book> getBooks() {
19 return books;
20 }
21
22 ArrayList<Person> people;
23 ArrayList<Book> books;
24
25 public MyLibrary(String name) {
26 this.name = name;
27 books = new ArrayList<Book>();
28 people = new ArrayList<Person>();
29
30 }
31
32 public void addBook(Book b1) {
33 this.books.add(b1);
34
35 }
36
37 public void removeBook(Book b1) {
38 this.books.remove(b1);
39
40 }
41
42 public void addPerson(Person p1){
43 this.people.add(p1);
44 }
45
46 public void removePerson(Person p1){
47 this.people.remove(p1);
48 }
49
50 public boolean checkOut(Book b1, Person p1) {
51 int booksOut = this.getBooksForPerson(p1).size();
52 if ((b1.getPerson() == null) &&
53 (booksOut < p1.getMaximumBooks())) {
54 b1.setPerson(p1);
55 return true;
56 }
57 else {
58 return false;
59 }
60 }
61
62 public boolean checkIn(Book b1) {
63 if (b1.getPerson() != null) {
64 b1.setPerson(null);
65 return true;
66 }
67 else {
68 return false;
69 }
70 }
71
72 public ArrayList<Book> getBooksForPerson(Person p1) {
73 ArrayList<Book> result = new ArrayList<Book>();
74 for (Book aBook : this.getBooks()) {
75 if (aBook.getPerson() != null &&
76 (aBook.getPerson().getName().equals(p1.getName()))) {
77 result.add(aBook);
78 }
79
80 }
81 return result;
82 }
83 }

原文地址:https://www.cnblogs.com/halflife/p/2079452.html