File size: 2,253 Bytes
63f6453
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * Kütüphane ödünç sistemi — arayüz (sözleşme) testleri için örnek.
 * Genel API:
 *   addBook(isbn, title)            -> boolean (yeni eklendiyse true)
 *   borrow(isbn, member)            -> IllegalStateException (ödünçte), NoSuchElementException (yok)
 *   giveBack(isbn)                  -> Optional<String> (iade eden üye)
 *   borrowedBy(member)              -> List<String> isbn (alfabetik sıralı)
 *   isAvailable(isbn)               -> boolean
 * Bir üye en fazla MAX_LOANS kitap ödünç alabilir.
 */
public class Library {
    public static final int MAX_LOANS = 3;
    private final Map<String, String> titles = new HashMap<>();
    private final Map<String, String> loans = new HashMap<>();

    public boolean addBook(String isbn, String title) {
        if (isbn == null || isbn.isBlank() || title == null || title.isBlank()) {
            throw new IllegalArgumentException("isbn and title are required");
        }
        return titles.putIfAbsent(isbn, title) == null;
    }

    public void borrow(String isbn, String member) {
        if (!titles.containsKey(isbn)) {
            throw new java.util.NoSuchElementException("unknown book: " + isbn);
        }
        if (loans.containsKey(isbn)) {
            throw new IllegalStateException("already borrowed");
        }
        if (borrowedBy(member).size() >= MAX_LOANS) {
            throw new IllegalStateException("loan limit reached");
        }
        loans.put(isbn, member);
    }

    public Optional<String> giveBack(String isbn) {
        return Optional.ofNullable(loans.remove(isbn));
    }

    public List<String> borrowedBy(String member) {
        List<String> out = new ArrayList<>();
        for (Map.Entry<String, String> e : loans.entrySet()) {
            if (e.getValue().equals(member)) {
                out.add(e.getKey());
            }
        }
        out.sort(String::compareTo);
        return out;
    }

    public boolean isAvailable(String isbn) {
        return titles.containsKey(isbn) && !loans.containsKey(isbn);
    }

    public int bookCount() {
        return titles.size();
    }
}