-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBookcaseMain.java
More file actions
232 lines (192 loc) · 7.82 KB
/
Copy pathBookcaseMain.java
File metadata and controls
232 lines (192 loc) · 7.82 KB
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
package com.startjava.graduation;
import java.time.Year;
import java.util.Scanner;
public class BookcaseMain {
private static final int SHELF_WIDTH = 44;
private static final String SHELF_LINE = "-".repeat(SHELF_WIDTH);
private static final int TYPING_DELAY_MS = 50;
private Bookcase bookcase;
private Scanner scanner;
public BookcaseMain() {
bookcase = new Bookcase();
scanner = new Scanner(System.in);
}
public static void main(String[] args) {
BookcaseMain main = new BookcaseMain();
main.start();
}
private void start() {
printWelcome();
boolean running = true;
while (running) {
printBookcase();
printMenu();
String choice = inputMenuItem();
running = executeCommand(choice);
if (running) {
waitEnter();
}
}
scanner.close();
System.out.println("\nПрограмма завершена. До свидания!");
}
private boolean executeCommand(String choice) {
switch (choice) {
case "1" -> addBook();
case "2" -> findBook();
case "3" -> deleteBook();
case "4" -> clearBookcase();
case "5" -> {
return false;
}
default -> System.out.println("Ошибка: неизвестная команда");
}
return true;
}
private void addBook() {
System.out.println("\n--- Добавление книги ---");
System.out.print("Введите автора: ");
String author = scanner.nextLine().trim();
System.out.print("Введите название: ");
String title = scanner.nextLine().trim();
Year year = inputYear();
try {
Book book = new Book(author, title, year);
if (bookcase.add(book)) {
System.out.println("\n✓ Книга успешно добавлена!");
} else {
System.out.println("\n✗ Ошибка: не удалось добавить книгу");
}
} catch (IllegalArgumentException e) {
System.out.println("\n✗ " + e.getMessage());
}
}
private void findBook() {
System.out.println("\n--- Поиск книги ---");
System.out.print("Введите название книги: ");
String title = scanner.nextLine().trim();
Book book = bookcase.find(title);
if (book != null) {
System.out.println("\n✓ Книга найдена: " + book);
} else {
System.out.println("\n✗ Книга с названием \"" + title + "\" не найдена");
}
}
private void deleteBook() {
System.out.println("\n--- Удаление книги ---");
System.out.print("Введите название книги: ");
String title = scanner.nextLine().trim();
if (bookcase.delete(title)) {
System.out.println("\n✓ Книга успешно удалена!");
} else {
System.out.println("\n✗ Книга с названием \"" + title + "\" не найдена");
}
}
private void clearBookcase() {
if (bookcase.getSize() == 0) {
System.out.println("\n✗ Шкаф уже пуст");
return;
}
System.out.print("\nВы уверены, что хотите удалить все книги? (yes/no): ");
String confirmation = scanner.nextLine().trim().toLowerCase();
if (confirmation.equals("yes")) {
bookcase.clear();
System.out.println("\n✓ Шкаф успешно очищен!");
} else {
System.out.println("\n✗ Операция отменена");
}
}
private void printWelcome() {
String welcome = """
╔════════════════════════════════════════════╗
║ ДОБРО ПОЖАЛОВАТЬ В КНИЖНЫЙ ШКАФ! ║
╚════════════════════════════════════════════╝
""";
typewriterEffect(welcome);
waitEnter();
}
private void printBookcase() {
System.out.println("\n" + "=".repeat(SHELF_WIDTH + 2));
System.out.println("В шкафу книг - " + bookcase.getSize() +
", свободно полок - " + bookcase.getFreeShelves());
System.out.println("=".repeat(SHELF_WIDTH + 2));
if (bookcase.getSize() == 0) {
System.out.println("\nШкаф пуст. Вы можете добавить в него первую книгу");
return;
}
Book[] books = bookcase.getBooks();
for (Book book : books) {
System.out.println("|" + formatBookForShelf(book) + "|");
System.out.println("|" + SHELF_LINE + "|");
}
}
private void printMenu() {
System.out.println("""
МЕНЮ:
1. Добавить книгу
2. Найти книгу
3. Удалить книгу
4. Очистить шкаф
5. Завершить
""");
}
private String inputMenuItem() {
while (true) {
System.out.print("Выберите пункт меню: ");
String input = scanner.nextLine().trim();
if (input.matches("[1-5]")) {
return input;
}
try {
Integer.parseInt(input);
System.out.println("Ошибка: Неверное значение меню (" + input +
"). Допустимые значения: 1-5");
} catch (NumberFormatException e) {
System.out.println("Ошибка: значение должно быть целым числом");
}
}
}
private Year inputYear() {
while (true) {
System.out.print("Введите год издания: ");
String input = scanner.nextLine().trim();
try {
return Year.of(Integer.parseInt(input));
} catch (NumberFormatException e) {
System.out.println("Ошибка: год должен быть целым числом");
System.out.println("Попробуйте еще раз:");
} catch (Exception e) {
System.out.println("Ошибка: некорректный год");
System.out.println("Попробуйте еще раз:");
}
}
}
private String formatBookForShelf(Book book) {
String bookStr = book.toString();
if (bookStr.length() > SHELF_WIDTH) {
return bookStr.substring(0, SHELF_WIDTH);
}
return bookStr + " ".repeat(SHELF_WIDTH - bookStr.length());
}
private void typewriterEffect(String text) {
for (char c : text.toCharArray()) {
System.out.print(c);
try {
Thread.sleep(TYPING_DELAY_MS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
break;
}
}
}
private void waitEnter() {
System.out.println("\nДля продолжения работы нажмите клавишу <Enter>");
while (true) {
String input = scanner.nextLine();
if (input.isEmpty()) {
break;
}
System.out.println("Ошибка: нажмите только <Enter>");
}
}
}