Skip to content

Commit 3290544

Browse files
committed
Merge remote-tracking branch 'origin/NikitaUdinDev' into PavelLeonovTeamLead
2 parents b278f80 + 948dae9 commit 3290544

File tree

7 files changed

+222
-112
lines changed

7 files changed

+222
-112
lines changed

src/main/java/App.java

Lines changed: 80 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,87 @@
1-
import userInterface.MenuManager;
1+
import dto.Client;
2+
import input.CustomCollection;
3+
import input.InputManager;
4+
import input.Strategy.FileReaderStrategy;
5+
import input.Strategy.ManualInputReaderStrategy;
6+
import input.Strategy.RandomDataGeneratorStrategy;
27

3-
import java.util.stream.IntStream;
8+
import java.io.IOException;
9+
import java.io.PrintStream;
10+
import java.nio.charset.StandardCharsets;
411

512
public class App {
6-
public static void main(String[] args) {
7-
MenuManager menuManager = new MenuManager();
13+
public static void main(String[] args) throws IOException {
14+
System.setOut(new PrintStream(System.out, true, StandardCharsets.UTF_8));
15+
////
16+
//// System.out.println("=== ТЕСТ FileReader ===");
17+
////
18+
//// try {
19+
//// FileReaderStrategy reader = new FileReaderStrategy("test_clients.txt");
20+
//// CustomCollection<Client> clients = reader.getData();
21+
////
22+
//// System.out.println("\n=== РЕЗУЛЬТАТ ===");
23+
//// System.out.println("Загружено клиентов: " + clients.size());
24+
//// System.out.println("Содержимое:");
25+
////
26+
//// int i = 1;
27+
//// for (Client client : clients) {
28+
//// System.out.println(i + ". " + client);
29+
//// i++;
30+
//// }
31+
////
32+
//// } catch (Exception e) {
33+
//// System.out.println("ФАТАЛЬНАЯ ОШИБКА: " + e.getMessage());
34+
//// e.printStackTrace();
35+
//// }
36+
////
37+
//// System.out.println("=== КОНЕЦ ТЕСТА === \n");
38+
////
39+
//// System.out.println("=== ТЕСТ RandomDataGenerator ===");
40+
////
41+
//// // Тест 1: Базовая генерация
42+
//// RandomDataGeneratorStrategy generator = new RandomDataGeneratorStrategy(5);
43+
//// CustomCollection<Client> clients = generator.getData();
44+
////
45+
//// System.out.println("Сгенерировано: " + clients.size() + " клиентов");
46+
//// clients.forEach(client -> System.out.println(" - " + client));
47+
////
48+
//// // Тест 2: С уникальными параметрами
49+
//// System.out.println("\n=== Тест с кастомным диапазоном ===");
50+
//// RandomDataGeneratorStrategy generator2 = new RandomDataGeneratorStrategy(3);
51+
//// CustomCollection<Client> clients2 = generator2.getData();
52+
////
53+
//// clients2.forEach(client ->
54+
//// System.out.println(" - " + client.getName() + ", ID: " + client.getIdNumber()));
55+
////
56+
//// System.out.println("=== КОНЕЦ ТЕСТА ===");
57+
//
58+
// System.out.println("=== ТЕСТ ManualInputReader ===\n");
59+
//
60+
// ManualInputReaderStrategy reader = new ManualInputReaderStrategy();
61+
// CustomCollection<Client> clients = reader.getData();
62+
//
63+
// System.out.println("\n=== РЕЗУЛЬТАТ ===");
64+
// System.out.println("Всего клиентов: " + clients.size());
65+
//
66+
// if (!clients.isEmpty()) {
67+
// System.out.println("Список:");
68+
// int i = 1;
69+
// for (Client client : clients) {
70+
// System.out.println(i + ". " + client);
71+
// i++;
72+
// }
73+
// }
74+
// System.out.println("=== КОНЕЦ ТЕСТА ===");
875

9-
menuManager.run();
76+
InputManager inputManager = new InputManager();
77+
inputManager.setStrategy(new FileReaderStrategy("test_clients.txt"));
78+
CustomCollection<Client> clients = inputManager.loadData();
79+
clients.forEach(System.out::println);
1080

81+
82+
// inputManager.setStrategy(inputManager.createManualStrategy());
83+
// CustomCollection<Client> clients2 = inputManager.loadData();
84+
// clients2.forEach(System.out::println);
1185
}
1286
}
87+
Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,14 @@
11
package input;
22

3-
public interface CollectionInterface<T> extends Iterable<String>{
4-
boolean add(T car); // important
5-
boolean remove(T car); // important
6-
boolean removeAt(int index);
3+
import java.util.stream.Stream;
4+
5+
public interface CollectionInterface<T> extends Iterable<T>{
6+
boolean add(T element); // important
7+
boolean remove(T element);// important
8+
void removeByIndex(int index);
79
void clear(); // important
810
T get(int index);
9-
boolean add(T car, int index);
1011
int size(); // important
11-
boolean contains(T car);
12+
boolean isEmpty();
13+
Stream<T> stream();
1214
}

src/main/java/input/CustomCollection.java

Lines changed: 24 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import java.util.Arrays;
44
import java.util.Iterator;
55
import java.util.NoSuchElementException;
6+
import java.util.Objects;
67
import java.util.stream.Stream;
78

89
/**
@@ -25,7 +26,7 @@
2526
*
2627
* @param <T> тип элементов, хранимых в коллекции
2728
*/
28-
public class CustomCollection<T> implements Iterable<T> {
29+
public class CustomCollection<T> implements CollectionInterface<T> {
2930
/** Коэффициент увеличения емкости при расширении массива. */
3031
private static final float GROWTH_FACTOR = 1.5f;
3132

@@ -57,6 +58,7 @@ public CustomCollection(int initialCapacity) {
5758
this.elements = new Object[initialCapacity];
5859
}
5960

61+
@Override
6062
public boolean add(T element) {
6163
// Проверяем достаточно ли места для добавления
6264
if (size == elements.length) {
@@ -70,6 +72,7 @@ public boolean add(T element) {
7072
return true;
7173
}
7274

75+
@Override
7376
public void removeByIndex(int index) {
7477
if (index < 0 || index >= size) {
7578
throw new IndexOutOfBoundsException("Index cannot be less then 0 or more then " + size);
@@ -90,20 +93,34 @@ public void removeByIndex(int index) {
9093
elements[--size] = null;
9194
}
9295

96+
@Override
97+
public boolean remove(T element) {
98+
for (int i = 0; i < size; i++) {
99+
if(Objects.equals(element, elements[i])) {
100+
removeByIndex(i);
101+
return true;
102+
}
103+
}
104+
return false;
105+
}
106+
107+
@Override
93108
public void clear() {
94109
for (int i = 0; i < size; i++) {
95110
elements[i] = null;
96111
}
97112
size = 0;
98113
}
99114

115+
@Override
100116
public T get(int index) {
101117
if (index < 0 || index >= size) {
102118
throw new IndexOutOfBoundsException("Индекс не может быть меньше 0 или больше " + size);
103119
}
104120
return (T) elements[index];
105121
}
106122

123+
107124
public T set(int index, T element) {
108125
if (index < 0 || index >= size) {
109126
throw new IndexOutOfBoundsException("Индекс не может быть меньше 0 или больше " + size);
@@ -121,6 +138,7 @@ public T set(int index, T element) {
121138
*
122139
* @return последовательный {@code Stream} элементов этой коллекции
123140
*/
141+
@Override
124142
public Stream<T> stream() {
125143
return (Stream<T>) Arrays.stream(elements, 0, size);
126144
}
@@ -135,32 +153,23 @@ public Stream<T> stream() {
135153
* в процессе выполнения операции.
136154
*
137155
* @param collection коллекция, содержащая элементы для добавления
138-
* @return {@code true} если эта коллекция изменилась в результате вызова
139156
*/
140-
public boolean addAll(CustomCollection<? extends T> collection) {
141-
// Проверяем, что переданная коллекция не null и не пустая
157+
public void addAll(CustomCollection<? extends T> collection) {
142158
if (collection == null || collection.isEmpty()) {
143-
// Возвращаем false, так как нечего добавлять
144-
return false;
159+
return;
145160
}
146161

147-
int requiredCapacity = size + collection.size();
148-
if (requiredCapacity > elements.length) {
149-
increaseCapacity(requiredCapacity);
150-
}
151162
for (T element : collection) {
152-
// Добавляем элемент в конец массива
153-
// elements[size] = element - добавляет элемент на текущую позицию
154-
// size++ - увеличивает счетчик элементов
155-
elements[size++] = element;
163+
add(element);
156164
}
157-
return true;
158165
}
159166

167+
@Override
160168
public int size() {
161169
return size;
162170
}
163171

172+
@Override
164173
public boolean isEmpty() {
165174
return size == 0;
166175
}

src/main/java/input/InputManager.java

Lines changed: 0 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -64,47 +64,4 @@ public CustomCollection<Client> loadData() throws IOException {
6464
}
6565
return currentStrategy.getData();
6666
}
67-
68-
/**
69-
* Создает стратегию для чтения данных из файла.
70-
*
71-
* <p>Файл должен содержать данные в формате:</p>
72-
* <pre>
73-
* Имя|Телефон|ID
74-
* Иван Иванов|+79991234567|1
75-
* </pre>
76-
*
77-
* @param filePath путь к файлу с данными о клиентах
78-
* @return стратегия чтения из файла
79-
* @throws IllegalArgumentException если {@code filePath} равен {@code null} или пуст
80-
*/
81-
public FileReaderStrategy createFileStrategy(String filePath) {
82-
if (filePath == null || filePath.trim().isEmpty()) {
83-
throw new IllegalArgumentException("Путь к файлу не может быть null или пустым");
84-
}
85-
return new FileReaderStrategy(filePath);
86-
}
87-
88-
/**
89-
* Создает стратегию для ручного ввода данных через консоль.
90-
*
91-
* <p>Стратегия предоставляет интерактивный интерфейс для ввода данных
92-
* о клиентах с валидацией и подтверждением.</p>
93-
*
94-
* @return стратегия ручного ввода
95-
*/
96-
public ManualInputReaderStrategy createManualStrategy() {
97-
return new ManualInputReaderStrategy();
98-
}
99-
100-
/**
101-
* Создает стратегию для генерации случайных данных о клиентах.
102-
*
103-
* @param count количество клиентов для генерации
104-
* @return стратегия генерации случайных данных
105-
* @throws IllegalArgumentException если {@code count} меньше или равен 0
106-
*/
107-
public RandomDataGeneratorStrategy createRandomStrategy(int count) {
108-
return new RandomDataGeneratorStrategy(count);
109-
}
11067
}

src/main/java/input/strategy/FileReaderStrategy.java

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -113,12 +113,12 @@ public Optional<Client.ClientBuilder> parseToClient(String line) {
113113
}
114114

115115
if (name.isEmpty()) {
116-
System.out.println("Пустое имя" + line);
116+
System.out.println("Пустое имя в строке: " + line);
117117
return Optional.empty();
118118
}
119119

120120
if (!phoneNumber.matches("^\\+7\\d{10}$")) {
121-
System.out.println("Неверный формат номера телефона" + line);
121+
System.out.println("Неверный формат номера телефона в строке: " + line);
122122
return Optional.empty();
123123
}
124124

@@ -129,7 +129,7 @@ public Optional<Client.ClientBuilder> parseToClient(String line) {
129129
return Optional.of(builder);
130130

131131
} catch (Exception e) {
132-
System.out.println("Ошибка" + line);
132+
System.out.println("Ошибка в строке: " + line);
133133
return Optional.empty();
134134
}
135135
}

0 commit comments

Comments
 (0)