diff --git a/src/main/java/ru/tn/courses/vbykov/v1/task1/subtask1.java b/src/main/java/ru/tn/courses/vbykov/v1/task1/subtask1.java new file mode 100644 index 00000000..a07a1161 --- /dev/null +++ b/src/main/java/ru/tn/courses/vbykov/v1/task1/subtask1.java @@ -0,0 +1,24 @@ +package ru.tn.courses.vbykov.v1.task1; +import java.util.Scanner; + +public class subtask1 { + /** + * (Задание 1 варианта) Дан массив натуральных чисел. Найти сумму элементов, кратных данному k. + **/ + + public static void main(String[] args) { + int[] array = new int[5]; + Scanner scanner = new Scanner(System.in); + System.out.println("введите k:"); + int k = scanner.nextInt(); + int sum = 0; + System.out.println("введите массив размера 5:"); + for (int i : array) { + array[i] = scanner.nextInt(); + if (array[i] % k == 0) { + sum += array[i]; + } + } + System.out.println("Сумма элементов массива кратных числу k = " + sum); + } +} diff --git a/src/main/java/ru/tn/courses/vbykov/v1/task1/subtask2.java b/src/main/java/ru/tn/courses/vbykov/v1/task1/subtask2.java new file mode 100644 index 00000000..dc6fd317 --- /dev/null +++ b/src/main/java/ru/tn/courses/vbykov/v1/task1/subtask2.java @@ -0,0 +1,30 @@ +package ru.tn.courses.vbykov.v1.task1; +import java.util.Scanner; + +public class subtask2 { + /** + * (Задание 1 варианта) У прилавка магазина выстроилась очередь из n покупателей. Время обслуживания i-того покупателя равно tj (i = 1, …, n). Определить время Ci пребывания i-гo покупателя в очереди. + **/ + + public static void main(String[] args) { + Scanner scanner = new Scanner(System.in); + System.out.println("Введите длину очереди n:"); + int n = scanner.nextInt(); + double[] t = new double[n]; + double[] c = new double[n]; + System.out.println("Введите время обслуживания i покупателя:"); + for (int i = 0; i < n; i++) { + t[i] = scanner.nextDouble(); + if (i == 0) { + c[i] = 0; + } + else { + c[i] = c[i - 1] + t[i - 1]; + } + } + System.out.println("Введите пребывания i покупателя в очереди:"); + for (int i = 0; i < n; i++) { + System.out.println(i + 1 + " покупатель : " + c[i] + " единиц времени в очереди"); + } + } +} diff --git a/src/main/java/ru/tn/courses/vbykov/v1/task1/subtask3.java b/src/main/java/ru/tn/courses/vbykov/v1/task1/subtask3.java new file mode 100644 index 00000000..1a36e2d3 --- /dev/null +++ b/src/main/java/ru/tn/courses/vbykov/v1/task1/subtask3.java @@ -0,0 +1,32 @@ +package ru.tn.courses.vbykov.v1.task1; +import java.util.Scanner; + +public class subtask3 { + /** + * (Задание 1 варианта) Даны две последовательности a1 ≤ a2 ≤ ... ≤ аn и b1 ≤ b2 ≤ ... ≤ bn. Образовать из них новую последовательность чисел так, чтобы она тоже была неубывающей (дополнительный массив не использовать). + **/ + + public static void main(String[] args) { + int[] a, b; + Scanner scanner = new Scanner(System.in); + System.out.println("Введите длину последовательностей n:"); + int n = scanner.nextInt(); + a = new int[n]; + b = new int[n]; + System.out.println("Введите последовательность a:"); + for (int i = 0; i < n; i++) { + a[i] = scanner.nextInt(); + } + System.out.println("Введите последовательность b:"); + for (int i = 0; i < n; i++) { + b[i] = scanner.nextInt(); + } + System.out.println("Новая последовательность без нового массива:"); + for (int i = 0, j = 0; i < n && j < n; j++) { + while (i < n && a[i] <= b[j]) { + System.out.println(a[i++]); + } + System.out.println(b[j]); + } + } +} diff --git a/src/main/java/ru/tn/courses/vbykov/v1/task2/Subtask.java b/src/main/java/ru/tn/courses/vbykov/v1/task2/Subtask.java new file mode 100644 index 00000000..4beb7c29 --- /dev/null +++ b/src/main/java/ru/tn/courses/vbykov/v1/task2/Subtask.java @@ -0,0 +1,86 @@ +package ru.tn.courses.vbykov.v1.task2; +import ru.tn.courses.vbykov.v1.task2.business.InternetShop; +import ru.tn.courses.vbykov.v1.task2.business.MyShop; +import ru.tn.courses.vbykov.v1.task2.models.Customer; +import ru.tn.courses.vbykov.v1.task2.repositories.CustomerRepository; +import ru.tn.courses.vbykov.v1.task2.repositories.OrderRepository; +import java.util.Scanner; + +public class Subtask { + + /** + * (Задание 1 варианта) + * - Необходимо разработать модель (класс) описывающий товар из интернет магазина (можно взять на свой выбор: телефоны, машины). + * - Необходимо разработать интерфейс для обработки заказов интернет магазина. + * - Реализовать классы обработки событий: создание заказа, изменения по заказу, возврат заказа. + * - Необходимо оформить все перечисления через enum + * - Вынести общую логику в абстракцию + **/ + + public static void main(String[] args) { + OrderRepository orderRepository = OrderRepository.getInstance(); + CustomerRepository customerRepository = CustomerRepository.getInstance(); + InternetShop shop = new MyShop(); + Scanner scanner = new Scanner(System.in); + System.out.println("введите команду: \n" + "exit: выйти\n" + "help: справка\n" + "create: создать заказ\n" + "return: вернуть товар\n" + "modif: изменить заказ\n" + "payment: оплатить\n" + "catalog: вывести католог товаров\n" + "orders: вывести список заказов\n"); + while (true) { + try { + switch (scanner.nextLine()) { + case "help": + System.out.println("exit: выйти\n" + "help: справка\n" + "create: создать заказ\n" + "return: вернуть товар\n" + "modif: изменить заказ\n" + "payment: оплатить\n" + "catalog: вывести католог товаров\n" + "orders: вывести список заказов\n" + "reg: регистрация пользователя\n" + "users: список пользователей"); + break; + case "exit": + System.exit(1); + break; + case "create": + System.out.println("Введите ваше имя: "); + String customerName = scanner.nextLine(); + System.out.println("Выберите товар который хотите купить: (введите id товара для покупки)"); + System.out.println(shop.catalog()); + shop.createOrder(Integer.valueOf(scanner.nextLine()), customerName); + System.out.println("Заказ был успешно создан"); + break; + case "orders": + System.out.println(orderRepository.findAll()); + break; + case "catalog": + System.out.println(shop.catalog()); + break; + case "modif": + System.out.println("Введите id заказа"); + Integer orderId = Integer.valueOf(scanner.nextLine()); + System.out.println("Выберите товар который хотите купить:"); + System.out.println(shop.catalog()); + shop.modifOrder(orderId, Integer.valueOf(scanner.nextLine())); + System.out.println("Заказ успешно изменен"); + break; + case "payment": + System.out.println("Введите id заказа"); + orderId = Integer.valueOf(scanner.nextLine()); + shop.payment(orderId); + System.out.println("Оплата успешно произведена"); + break; + case "return": + System.out.println("Введите id заказа:"); + shop.returnProduct(Integer.valueOf(scanner.nextLine())); + System.out.println("Возврат успешно выполнен"); + break; + case "reg": + System.out.println("Введите имя"); + String name = scanner.nextLine(); + System.out.println("Введите скок денег на счету XD"); + customerRepository.save(new Customer(customerRepository.getSize(), name, Double.valueOf(scanner.nextLine()))); + System.out.println("Пользователь успешно создан"); + break; + case "users": + System.out.println(customerRepository.findAll()); + break; + default: + System.out.println("Команда не понятна, help - справка"); + } + } catch (Exception e) { + System.out.println(e.getMessage()); + } + } + } +} diff --git a/src/main/java/ru/tn/courses/vbykov/v1/task2/businees/InternetShop.java b/src/main/java/ru/tn/courses/vbykov/v1/task2/businees/InternetShop.java new file mode 100644 index 00000000..9f89fa64 --- /dev/null +++ b/src/main/java/ru/tn/courses/vbykov/v1/task2/businees/InternetShop.java @@ -0,0 +1,12 @@ +package ru.tn.courses.vbykov.v1.task2.business; +import ru.tn.courses.vbykov.v1.task2.models.Order; +import ru.tn.courses.vbykov.v1.task2.models.Product; +import java.util.List; + +public interface InternetShop { + Order createOrder(Integer productId, String customer) throws Exception; + Order payment(Integer orderId) throws Exception; + Order returnProduct(Integer orderId) throws Exception; + Order modifOrder(Integer orderId, Integer productId) throws Exception; + List catalog(); +} diff --git a/src/main/java/ru/tn/courses/vbykov/v1/task2/businees/MyShop.java b/src/main/java/ru/tn/courses/vbykov/v1/task2/businees/MyShop.java new file mode 100644 index 00000000..e80e9fa6 --- /dev/null +++ b/src/main/java/ru/tn/courses/vbykov/v1/task2/businees/MyShop.java @@ -0,0 +1,81 @@ +package ru.tn.courses.vbykov.v1.task2.business; +import ru.tn.courses.vbykov.v1.task2.enums.OrderDescriptionEnum; +import ru.tn.courses.vbykov.v1.task2.models.Customer; +import ru.tn.courses.vbykov.v1.task2.models.Order; +import ru.tn.courses.vbykov.v1.task2.models.Product; +import ru.tn.courses.vbykov.v1.task2.repositories.CustomerRepository; +import ru.tn.courses.vbykov.v1.task2.repositories.OrderRepository; +import ru.tn.courses.vbykov.v1.task2.repositories.ProductRepository; +import java.time.LocalDate; +import java.util.List; + +public class MyShop implements InternetShop { + OrderRepository orderRepository = OrderRepository.getInstance(); + ProductRepository productRepository = ProductRepository.getInstance(); + CustomerRepository customerRepository = CustomerRepository.getInstance(); + @Override + public Order createOrder(Integer productId, String customerName) throws Exception { + Customer customer = customerRepository.findByName(customerName); + try { + Product product = productRepository.findById(productId); + Order order = + new Order(orderRepository.getSize(), customer, product, OrderDescriptionEnum.CREATE.getValue()); + orderRepository.save(order); + return order; + } catch (Exception e) { + throw new Exception("Товар с таким id не найден"); + } + } + @Override + public Order payment(Integer orderId) throws Exception { + try { + Order order = orderRepository.findById(orderId); + order.setDescription(OrderDescriptionEnum.BUY.getValue()); + Customer customer = customerRepository.findById(order.getCustomer().getId()); + Product product = productRepository.findById(order.getProduct().getId()); + if (product.getCount() > 0) { + product.setCount(product.getCount() - 1); + } else { + throw new Exception("Товара больше нет"); + } + if (order.getProduct().getPrice() > customer.getMoney()) { + throw new Exception("На вашем счете недосаточного денег"); + } + productRepository.update(product, product.getId()); + order.setPayment(order.getProduct().getPrice()); + customer.setMoney(customer.getMoney() - order.getProduct().getPrice()); + customerRepository.update(customer, customer.getId()); + return order; + } catch (IndexOutOfBoundsException e) { + throw new Exception("Заказ с таким id не найден"); + } + } + @Override + public Order returnProduct(Integer orderId) throws Exception { + try { + Order order = orderRepository.findById(orderId); + order.setDescription(OrderDescriptionEnum.RETURN.getValue()); + orderRepository.update(order, orderId); + return order; + } catch (Exception e) { + throw new Exception("Заказа с таким id не найдено."); + } + } + @Override + public Order modifOrder(Integer orderId, Integer newProductId) throws Exception { + try { + Product newProduct = productRepository.findById(newProductId); + Order order = orderRepository.findById(orderId); + order.setModified(LocalDate.now()); + order.setProduct(newProduct); + order.setDescription(OrderDescriptionEnum.MODIF.getValue()); + return order; + } catch (Exception e) { + throw new Exception("Товар или заказ с таким id не найдено"); + } + } + @Override + public List catalog() { + return productRepository.findAll(); + } +} diff --git a/src/main/java/ru/tn/courses/vbykov/v1/task2/enums/BrandEnum.java b/src/main/java/ru/tn/courses/vbykov/v1/task2/enums/BrandEnum.java new file mode 100644 index 00000000..f80c19ab --- /dev/null +++ b/src/main/java/ru/tn/courses/vbykov/v1/task2/enums/BrandEnum.java @@ -0,0 +1,12 @@ +package ru.tn.courses.vbykov.v1.task2.enums; + +public enum BrandEnum { + Samsung("Самсунг"), Huawei("Хуавэй"), Xiaomi("Ксяоми"); + private final String value; + BrandEnum(String value) { + this.value = value; + } + public String getValue() { + return value; + } +} diff --git a/src/main/java/ru/tn/courses/vbykov/v1/task2/enums/ColorEnum.java b/src/main/java/ru/tn/courses/vbykov/v1/task2/enums/ColorEnum.java new file mode 100644 index 00000000..17f70963 --- /dev/null +++ b/src/main/java/ru/tn/courses/vbykov/v1/task2/enums/ColorEnum.java @@ -0,0 +1,12 @@ +package ru.tn.courses.vbykov.v1.task2.enums; + +public enum ColorEnum{ + BLACK("Черный"), WHITE("Белый"), BLUE("Синий"); + private final String value; + ColorEnum(String value) { + this.value = value; + } + public String getValue() { + return value; + } +} diff --git a/src/main/java/ru/tn/courses/vbykov/v1/task2/enums/DisplayResolutionEnum.java b/src/main/java/ru/tn/courses/vbykov/v1/task2/enums/DisplayResolutionEnum.java new file mode 100644 index 00000000..5c292331 --- /dev/null +++ b/src/main/java/ru/tn/courses/vbykov/v1/task2/enums/DisplayResolutionEnum.java @@ -0,0 +1,12 @@ +package ru.tn.courses.vbykov.v1.task2.enums; + +public enum DisplayResolutionEnum { + STANDART("1080×1920"), PLUS("1440 x 2960"); + private final String value; + DisplayResolutionEnum(String value) { + this.value = value; + } + public String getValue() { + return value; + } +} diff --git a/src/main/java/ru/tn/courses/vbykov/v1/task2/enums/OperatingSystemEnum.java b/src/main/java/ru/tn/courses/vbykov/v1/task2/enums/OperatingSystemEnum.java new file mode 100644 index 00000000..deae0589 --- /dev/null +++ b/src/main/java/ru/tn/courses/vbykov/v1/task2/enums/OperatingSystemEnum.java @@ -0,0 +1,12 @@ +package ru.tn.courses.vbykov.v1.task2.enums; + +public enum OperatingSystemEnum { + Android("Андроид"), Ubuntu_Touch("Убунту Тоуч"), SIRIN_OS("СИРИН ОС"); + private final String value; + OperatingSystemEnum(String value) { + this.value = value; + } + public String getValue() { + return value; + } +} diff --git a/src/main/java/ru/tn/courses/vbykov/v1/task2/enums/OrderDescriptionEnum.java b/src/main/java/ru/tn/courses/vbykov/v1/task2/enums/OrderDescriptionEnum.java new file mode 100644 index 00000000..a0782fa6 --- /dev/null +++ b/src/main/java/ru/tn/courses/vbykov/v1/task2/enums/OrderDescriptionEnum.java @@ -0,0 +1,12 @@ +package ru.tn.courses.vbykov.v1.task2.enums; + +public enum OrderDescriptionEnum { + CREATE("Создание заказа"), RETURN("Возврат продукта"), MODIF("Изменение заказа"), BUY("Произведение покупки"); + private final String value; + OrderDescriptionEnum(String value) { + this.value = value; + } + public String getValue() { + return value; + } +} diff --git a/src/main/java/ru/tn/courses/vbykov/v1/task2/models/Customer.java b/src/main/java/ru/tn/courses/vbykov/v1/task2/models/Customer.java new file mode 100644 index 00000000..66bba39e --- /dev/null +++ b/src/main/java/ru/tn/courses/vbykov/v1/task2/models/Customer.java @@ -0,0 +1,27 @@ +package ru.tn.courses.vbykov.v1.task2.models; + +public class Customer extends Model{ + String name; + Double money; + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + public Double getMoney() { + return money; + } + public void setMoney(Double money) { + this.money = money; + } + public Customer(Integer id, String name, Double money) { + super(id); + this.name = name; + this.money = money; + } + @Override + public String toString() { + return super.toString() + "; name: " + name + "; money: " + money + "\n"; + } +} diff --git a/src/main/java/ru/tn/courses/vbykov/v1/task2/models/Model.java b/src/main/java/ru/tn/courses/vbykov/v1/task2/models/Model.java new file mode 100644 index 00000000..f44247c0 --- /dev/null +++ b/src/main/java/ru/tn/courses/vbykov/v1/task2/models/Model.java @@ -0,0 +1,15 @@ +package ru.tn.courses.vbykov.v1.task2.models; + +public class Model { + private Integer id; + public Integer getId() { + return id; + } + public Model(Integer id) { + this.id = id; + } + @Override + public String toString() { + return "id: " + id; + } +} diff --git a/src/main/java/ru/tn/courses/vbykov/v1/task2/models/Order.java b/src/main/java/ru/tn/courses/vbykov/v1/task2/models/Order.java new file mode 100644 index 00000000..4bfab2d3 --- /dev/null +++ b/src/main/java/ru/tn/courses/vbykov/v1/task2/models/Order.java @@ -0,0 +1,57 @@ +package ru.tn.courses.vbykov.v1.task2.models; +import java.time.LocalDate; + +public class Order extends Model { + private Customer customer; + private LocalDate created; + private LocalDate modified; + private Product product; + private String description; + private double payment; + public double getPayment() { + return payment; + } + public void setPayment(double payment) { + this.payment = payment; + } + public Order(Integer id, Customer customer, Product product, String description) { + super(id); + this.customer = customer; + this.created = LocalDate.now(); + this.modified = LocalDate.now(); + this.product = product; + this.description = description; + } + public Customer getCustomer() { + return customer; + } + public Product getProduct() { + return product; + } + public void setProduct(Product product) { + this.product = product; + } + public void setCustomer(Customer customer) { + this.customer = customer; + } + public LocalDate getModified() { + return modified; + } + public void setModified(LocalDate modified) { + this.modified = modified; + } + public LocalDate getCreated() { + return created; + } + public String getDescription() { + return description; + } + public void setDescription(String description) { + this.description = description; + } + @Override + public String toString() { + return super.toString() + "; customer: " + customer.name + "; created: " + created + "; product: {" + product + + "}; description: " + description + "\n"; + } +} diff --git a/src/main/java/ru/tn/courses/vbykov/v1/task2/models/Product.java b/src/main/java/ru/tn/courses/vbykov/v1/task2/models/Product.java new file mode 100644 index 00000000..cf391d9a --- /dev/null +++ b/src/main/java/ru/tn/courses/vbykov/v1/task2/models/Product.java @@ -0,0 +1,27 @@ +package ru.tn.courses.vbykov.v1.task2.models; + +public class Product extends Model{ + private double price; + private int count; + public Product(Integer id, double price, int count) { + super(id); + this.price = price; + this.count = count; + } + public double getPrice() { + return price; + } + public void setPrice(double price) { + this.price = price; + } + public int getCount() { + return count; + } + public void setCount(int count) { + this.count = count; + } + @Override + public String toString() { + return super.toString() + "; price: " + price + "; count: "+ count; + } +} diff --git a/src/main/java/ru/tn/courses/vbykov/v1/task2/models/Smartphone.java b/src/main/java/ru/tn/courses/vbykov/v1/task2/models/Smartphone.java new file mode 100644 index 00000000..c4b3c91d --- /dev/null +++ b/src/main/java/ru/tn/courses/vbykov/v1/task2/models/Smartphone.java @@ -0,0 +1,44 @@ +package ru.tn.courses.vbykov.v1.task2.models; + +public class Smartphone extends Product { + private String Color; + private String Brand; + private String Display_Resolution; + private String Operating_System; + + public Smartphone(Integer id, String Color, String Brand, double price, String Display_Resolution, String Operating_System, int count) { + super(id, price, count); + this.Color = Color; + this.Brand = Brand; + this.Display_Resolution = Display_Resolution; + this.Operating_System = Operating_System; + } + public String getColor() { + return Color; + } + public void setColor(String Color) { + this.Color = Color; + } + public String getBrand() { + return Brand; + } + public void setBrand(String Brand) { + this.Brand = Brand; + } + public String getDisplay_Resolution() { + return Display_Resolution; + } + public void setDisplay_Resolution(String Display_Resolution) { + this.Display_Resolution = Display_Resolution; + } + public String getOperating_System() { + return Operating_System; + } + public void setOperating_System(String Operating_System) { + this.Operating_System = Operating_System; + } + @Override + public String toString() { + return super.toString() + "; Color : " + Color + "; Brand: " + Brand + "; Display_Resolution: " + Display_Resolution + "; Operating_System: " + Operating_System + "\n"; + } +} diff --git a/src/main/java/ru/tn/courses/vbykov/v1/task2/repositories/CustomerRepository.java b/src/main/java/ru/tn/courses/vbykov/v1/task2/repositories/CustomerRepository.java new file mode 100644 index 00000000..40a5ff8b --- /dev/null +++ b/src/main/java/ru/tn/courses/vbykov/v1/task2/repositories/CustomerRepository.java @@ -0,0 +1,27 @@ +package ru.tn.courses.vbykov.v1.task2.repositories; +import ru.tn.courses.vbykov.v1.task2.models.Customer; +import java.util.ArrayList; +import java.util.List; + +public class CustomerRepository extends RepositoryImpl { + private static CustomerRepository instance; + public static CustomerRepository getInstance() { + if (instance == null) { + instance = new CustomerRepository(); + } + return instance; + } + public CustomerRepository() { + super(new ArrayList<>()); + save(new Customer(getSize(), "Анастасия", 10000.0)); + save(new Customer(getSize(), "Григорий", 100.0)); + } + public Customer findByName(String name) throws Exception { + List allCustomer = findAll(); + for (Customer customer : allCustomer) { + if (customer.getName().equals(name)) + return customer; + } + throw new Exception("Покупателя с таким именем не найдено."); + } +} diff --git a/src/main/java/ru/tn/courses/vbykov/v1/task2/repositories/OrderRepository.java b/src/main/java/ru/tn/courses/vbykov/v1/task2/repositories/OrderRepository.java new file mode 100644 index 00000000..3eb81d76 --- /dev/null +++ b/src/main/java/ru/tn/courses/vbykov/v1/task2/repositories/OrderRepository.java @@ -0,0 +1,16 @@ +package ru.tn.courses.vbykov.v1.task2.repositories; +import ru.tn.courses.vbykov.v1.task2.models.Order; +import java.util.ArrayList; + +public class OrderRepository extends RepositoryImpl { + private static OrderRepository instance; + public static OrderRepository getInstance(){ + if(instance == null){ + instance = new OrderRepository(); + } + return instance; + } + public OrderRepository() { + super(new ArrayList<>()); + } +} diff --git a/src/main/java/ru/tn/courses/vbykov/v1/task2/repositories/ProductRepository.java b/src/main/java/ru/tn/courses/vbykov/v1/task2/repositories/ProductRepository.java new file mode 100644 index 00000000..1c352af0 --- /dev/null +++ b/src/main/java/ru/tn/courses/vbykov/v1/task2/repositories/ProductRepository.java @@ -0,0 +1,48 @@ +package ru.tn.courses.vbykov.v1.task2.repositories; +import ru.tn.courses.vbykov.v1.task2.enums.BrandEnum; +import ru.tn.courses.vbykov.v1.task2.enums.ColorEnum; +import ru.tn.courses.vbykov.v1.task2.enums.OperatingSystemEnum; +import ru.tn.courses.vbykov.v1.task2.enums.DisplayResolutionEnum; +import ru.tn.courses.vbykov.v1.task2.models.Smartphone; +import ru.tn.courses.vbykov.v1.task2.models.Product; +import java.util.ArrayList; + +public class ProductRepository extends RepositoryImpl { + private static ProductRepository instance; + public static ProductRepository getInstance(){ + if(instance == null){ + instance = new ProductRepository(); + } + return instance; + } + private ProductRepository() { + super(new ArrayList<>()); + save( + new Smartphone( + getSize(), + ColorEnum.BLUE.getValue(), + BrandEnum.Samsung.getValue(), + 1500, + DisplayResolutionEnum.PLUS.getValue(), + OperatingSystemEnum.Android.getValue(), + 8)); + save( + new Smartphone( + getSize(), + ColorEnum.BLACK.getValue(), + BrandEnum.Xiaomi.getValue(), + 1500, + DisplayResolutionEnum.STANDART.getValue(), + OperatingSystemEnum.Android.getValue(), + 10)); + save( + new Smartphone( + getSize(), + ColorEnum.WHITE.getValue(), + BrandEnum.Huawei.getValue(), + 2000, + DisplayResolutionEnum.STANDART.getValue(), + OperatingSystemEnum.Ubuntu_Touch.getValue(), + 15)); + } +} diff --git a/src/main/java/ru/tn/courses/vbykov/v1/task2/repositories/Repository.java b/src/main/java/ru/tn/courses/vbykov/v1/task2/repositories/Repository.java new file mode 100644 index 00000000..dc880763 --- /dev/null +++ b/src/main/java/ru/tn/courses/vbykov/v1/task2/repositories/Repository.java @@ -0,0 +1,10 @@ +package ru.tn.courses.vbykov.v1.task2.repositories; +import java.util.List; + +public interface Repository { + List findAll(); + void save(T var); + void update(T var, Integer id); + T findById(Integer id); + Integer getSize(); +} diff --git a/src/main/java/ru/tn/courses/vbykov/v1/task2/repositories/RepositoryImpl.java b/src/main/java/ru/tn/courses/vbykov/v1/task2/repositories/RepositoryImpl.java new file mode 100644 index 00000000..27e34192 --- /dev/null +++ b/src/main/java/ru/tn/courses/vbykov/v1/task2/repositories/RepositoryImpl.java @@ -0,0 +1,29 @@ +package ru.tn.courses.vbykov.v1.task2.repositories; +import java.util.List; + +public class RepositoryImpl implements Repository< + private List repository; + public RepositoryImpl(List + this. + } + @Override + public List + return repository; + } + @Override + public void save(T + repository.add( + } + @Override + public void update(T var, Integer id) { + repository.set(id, var); + } + @Override + public T findById(Integer id) { + return repository.get(id); + } + @Override + public Integer getSize() { + return repository.size(); + } +} diff --git a/src/main/java/ru/tn/courses/vbykov/v1/task3/Integer.java b/src/main/java/ru/tn/courses/vbykov/v1/task3/Integer.java new file mode 100644 index 00000000..09c2ba16 --- /dev/null +++ b/src/main/java/ru/tn/courses/vbykov/v1/task3/Integer.java @@ -0,0 +1,124 @@ +package ru.tn.courses.vbykov.v1.task3; + +public class Integer { + private final int value; + public final static int MAX_VALUE = 0x7fffffff; + public final static int MIN_VALUE = 0x80000000; + public int getValue() { + return this.value; + } + public Integer() { + this.value = 0; + } + public Integer(int x) { + this.value = x; + } + public Integer(String s) throws RuntimeException { + if (s == null) { + throw new RuntimeException(); + } + this.value = parseInt(s); + } + private int parseInt(String s) throws RuntimeException { + int x = 0; + int f = 1; + byte[] bytes = s.getBytes(); + int i = 0; + if (bytes[i] == '-') { + i++; + f = -1; + } + while (i < bytes.length) { + if (bytes[i] >= '0' && bytes[i] <= '9') { + if (((long) x * 10 + bytes[i] - '0') > MAX_VALUE) { + throw new RuntimeException("выход за границы"); + } + x = x * 10 + bytes[i++] - '0'; + } else { + throw new RuntimeException(); + } + } + return x * f; + } + @Override + public String toString() { + return String.valueOf(value); + } + public boolean equals(Object o) { + if (o instanceof Integer) { + return value == ((Integer) o).getValue(); + } + return false; + } + public int hashCode() { + return this.value; + } + public Integer add(Integer i) { + if (((long) this.value + i.getValue()) > MAX_VALUE) { + throw new RuntimeException("выход за пределы"); + } + return new Integer(this.value + i.getValue()); + } + public Integer diff(Integer i) { + if (((long) this.value - i.getValue()) < MIN_VALUE) { + throw new RuntimeException("выход за пределы"); + } + return new Integer(this.value - i.getValue()); + } + public Integer mult(Integer i) { + if (((long) this.value * i.getValue()) > MAX_VALUE) { + throw new RuntimeException("выход за пределы"); + } + return new Integer(this.value * i.getValue()); + } + public Integer div(Integer i) { + if (i.getValue() == 0) { + throw new RuntimeException("на ноль делить нельзя..."); + } + return new Integer(this.value / i.getValue()); + } + public Integer mod(Integer i) { + if (i.getValue() == 0) { + throw new RuntimeException("деление на ноль"); + } + return new Integer(this.value % i.getValue()); + } + public Integer pow(int exponent) { + if (exponent == 1) { + return this; + } + if (exponent == 0) { + return new Integer(1); + } + int x = this.value; + for (int i = 1; i < exponent; i++) { + if (((long) x * value) > MAX_VALUE) { + throw new RuntimeException("выход за пределы"); + } + x *= value; + } + return new Integer(x); + } + public String toOctalString() { + String s = ""; + int x = this.value; + while (x > 0) { + s = (char) ((x % 8) + '0') + s; + x /= 8; + } + return s; + } + public String toHexString() { + String s = ""; + int x = this.value; + while (x > 0) { + if (x % 16 > 9) { + s = (char) ((x % 16) + 'A' - 10) + s; + } else { + s = (char) ((x % 16) + '0') + s; + } + x /= 16; + } + return s; + } +} diff --git a/src/main/java/ru/tn/courses/vbykov/v1/task3/ListContainer.java b/src/main/java/ru/tn/courses/vbykov/v1/task3/ListContainer.java new file mode 100644 index 00000000..0c9bfb4c --- /dev/null +++ b/src/main/java/ru/tn/courses/vbykov/v1/task3/ListContainer.java @@ -0,0 +1,131 @@ +package ru.tn.courses.vbykov.v1.task3; +import java.util.Collection; + +public class ListContainer { + private T[] values; + private int size; + public ListContainer() { + this.values = (T[]) new Object[10]; + this.size = 0; + } + public ListContainer(T... values) { + this.values = (T[]) new Object[values.length]; + for (int i = 0; i < values.length; i++) { + this.add(values[i]); + } + } + public T[] getValues() { + var list = (T[]) new Object[this.size]; + for (int i = 0; i < this.size; i++) { + list[i] = this.values[i]; + } + return list; + } + public void add(T value) { + if (this.size < this.values.length) { + this.values[size++] = value; + } else { + T[] temp = (T[]) new Object[2 * size]; + for (int i = 0; i < size; i++) { + temp[i] = this.values[i]; + } + this.values = temp; + this.values[size++] = value; + } + } + public void add(T value, int index) { + if (this.values.length >= this.size + 1) { + T[] temp = (T[]) new Object[2 * size]; + for (int i = 0; i < size; i++) { + temp[i] = (T) this.values[i]; + } + this.values = temp; + } + for (int i = size; i > index; i--) { + this.values[i] = this.values[i - 1]; + } + if (index > size) { + add(value); + } else { + this.values[index] = value; + } + } + public void remove(int index) { + if (index < this.size) { + for (int i = index; i <= this.size - 1; i++) { + this.values[i] = this.values[i + 1]; + } + size--; + } else { + throw new RuntimeException("за пределами массива"); + } + } + public T get(int index) { + if (index <= size) { + return (T) this.values[index]; + } else { + throw new RuntimeException("за пределами массива"); + } + } + public T get(T value) { + int i = 0; + while (i < size) { + if (value.equals(this.values[i])) { + return (T) this.values[i]; + } + i++; + } + return null; + } + public boolean equals(final Object o) { + if (o == this) { + return true; + } + if (!(o instanceof ListContainer)) { + return false; + } + var listConteiners = (ListContainer) o; + for (int i = 0; i < size; i++) { + if (!listConteiners.values[i].equals(this.values[i])) { + return false; + } + } + return true; + } + @Override + public int hashCode() { + int hash = 0; + for (int i = 0; i < size; i++) { + hash += 13 * hash + this.values[i].hashCode(); + } + return hash; + } + public void addCollection(Collection collection) { + T[] collectionElements = (T[]) new Object[collection.size()]; + int i = 0; + for (T element : collection) { + collectionElements[i++] = element; + } + + for (i = 0; i < collectionElements.length; i++) { + add(collectionElements[i]); + } + } + public int getSize() { + return this.size; + } + public ListContainer getSubConteiner(int[] indexes) { + var listContainer = new ListContainer(); + for (int i = 0; i < indexes.length; i++) { + if (indexes[i] > size) { + throw new RuntimeException("индекс за пределами массива"); + } + listContainer.add(this.values[indexes[i]]); + } + return listContainer; + } + public String toString() { + // это ток для себя, не использую arrays utils + return "(values=" + java.util.Arrays.deepToString(this.getValues()) + ", size=" + this.getSize() + ")"; + } +} diff --git a/src/main/java/ru/tn/courses/vbykov/v1/task3/Subtask_1.java b/src/main/java/ru/tn/courses/vbykov/v1/task3/Subtask_1.java new file mode 100644 index 00000000..59ee3ad2 --- /dev/null +++ b/src/main/java/ru/tn/courses/vbykov/v1/task3/Subtask_1.java @@ -0,0 +1,20 @@ +package ru.tn.courses.vbykov.v1.task3; + +public class Subtask_1 { + /** + * (Задание 1 варианта) Разработать класс Integer + * - класс должен содержать конструкторы Integer(), Integer(int x), Integer(String s) + * - Реализовать метод сравнения двух объектов класса Integer + * - Реализовать методы добавления значения add(Integer i), вычитания, умножения и деления + * - Реализовать метод возведения в степень pow(int exponent) + * - реализовать методы преставления числа в восьмеричной и шестнадцатеричной СС + */ + public static void main(String[] args) { + Integer a = new Integer(0); + Integer b = new Integer("-2"); + Integer c = b.pow(2); + System.out.println(c); + System.out.println(c.toOctalString()); + System.out.println(c.toHexString()); + } +} diff --git a/src/main/java/ru/tn/courses/vbykov/v1/task3/Subtask_2.java b/src/main/java/ru/tn/courses/vbykov/v1/task3/Subtask_2.java new file mode 100644 index 00000000..28b171e0 --- /dev/null +++ b/src/main/java/ru/tn/courses/vbykov/v1/task3/Subtask_2.java @@ -0,0 +1,34 @@ +package ru.tn.courses.vbykov.v1.task3; +import java.lang.reflect.Array; +import java.util.Arrays; +import java.util.Collection; +import java.util.Set; +import java.util.stream.Stream; + +public class Subtask_2 { + /** + * Разработать класс ListContainer для хранения дженерик списков + * - класс должен содержать конструктор по умолчанию и конструктор с new ListContainer(T ... elements) + * - метод получения значения списка + * - метод сравнения двух контейнеров + * - методы добавления и удаления элемента в контейнер + * - методы поиска элементов по индексу или значению + * - добавление коллекции элементов + * - получение контейнера с подсписком по индексам + */ + public static void main(String[] args) { + ListContainer listContainer = new ListContainer<>(1, 2, 3); + listContainer.addCollection(Set.of(1, 2, 3)); + System.out.println(listContainer); + listContainer.add(2); + System.out.println(listContainer); + listContainer.add(4, 6); + System.out.println(listContainer); + listContainer.remove(3); + System.out.println(listContainer); +// Arrays.stream(listContainer.getValues()).forEach(System.out::println); + System.out.println(listContainer.get(3)); + var listContainer2 = listContainer.getSubConteiner(new int[]{1,2,3}); + System.out.println(listContainer2); + } +}