Skip to content

lab 3 #21

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions src/main/java/ru/tn/courses/vbogatyrev/v1/task1/Subtask_1.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package ru.tn.courses.vbogatyrev.v1.task1;

import java.util.Scanner;

public class Subtask_1 {
/**
* Дан массив натуральных чисел. Найти сумму элементов, кратных данному K.
**/

public static void main(String[] args) {

int[] array = new int[10];
Scanner scanner = new Scanner(System.in);

System.out.println("введите k:");

int k = scanner.nextInt();
int sum = 0;

System.out.println("введите массив размера 10:");

for (int i : array) {
array[i] = scanner.nextInt();
if (array[i] % k == 0) {
sum += array[i];
}
}

System.out.println("сумма элементов массива кратных числу k = " + sum);
}
}
36 changes: 36 additions & 0 deletions src/main/java/ru/tn/courses/vbogatyrev/v1/task1/Subtask_2.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package ru.tn.courses.vbogatyrev.v1.task1;

import java.util.Scanner;

public class Subtask_2 {
/**
* У прилавка магазина выстроилась очередь из 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] + " единиц времени в очереди");
}
}
}
39 changes: 39 additions & 0 deletions src/main/java/ru/tn/courses/vbogatyrev/v1/task1/Subtask_3.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package ru.tn.courses.vbogatyrev.v1.task1;

import java.util.Scanner;

public class Subtask_3 {
/**
* Даны две последовательности a1 ≤ a2 ≤ ... ≤ аn и b1 ≤ b2 ≤ ... ≤ bn. Образовать из них новую последовательность
* чисел так, чтобы она тоже была неубывающей (дополнительный массив не использовать).
*/

public static void main(String[] args) {
int[] a, b, c;
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]);
}
}
}
94 changes: 94 additions & 0 deletions src/main/java/ru/tn/courses/vbogatyrev/v1/task2/Subtask_2.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
package ru.tn.courses.vbogatyrev.v1.task2;

import ru.tn.courses.vbogatyrev.v1.task2.business.InternetShop;
import ru.tn.courses.vbogatyrev.v1.task2.business.MyShop;
import ru.tn.courses.vbogatyrev.v1.task2.models.Customer;
import ru.tn.courses.vbogatyrev.v1.task2.repositories.CustomerRepository;
import ru.tn.courses.vbogatyrev.v1.task2.repositories.OrderRepository;

import java.util.Scanner;

public class Subtask_2 {

/**
* - Необходимо разработать модель (класс) описывающий товар из интернет магазина (можно взять на свой выбор:
* телефоны, машины). - Необходимо разработать интерфейс для обработки заказов интернет магазина. - Реализовать
* классы обработки событий: создание заказа, изменения по заказу, возврат заказа. - Необходимо оформить все
* перечисления через 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());
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package ru.tn.courses.vbogatyrev.v1.task2.business;

import ru.tn.courses.vbogatyrev.v1.task2.models.Order;
import ru.tn.courses.vbogatyrev.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<Product> catalog();
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
package ru.tn.courses.vbogatyrev.v1.task2.business;

import ru.tn.courses.vbogatyrev.v1.task2.enums.OrderDescriptionEnum;
import ru.tn.courses.vbogatyrev.v1.task2.models.Customer;
import ru.tn.courses.vbogatyrev.v1.task2.models.Order;
import ru.tn.courses.vbogatyrev.v1.task2.models.Product;
import ru.tn.courses.vbogatyrev.v1.task2.repositories.CustomerRepository;
import ru.tn.courses.vbogatyrev.v1.task2.repositories.OrderRepository;
import ru.tn.courses.vbogatyrev.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<Product> catalog() {
return productRepository.findAll();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package ru.tn.courses.vbogatyrev.v1.task2.enums;

public enum BrandEnum {
AUDI("ауди"), VAZ("вишневая семерка"), BMW("бмв");

private final String value;

BrandEnum(String value) {
this.value = value;
}

public String getValue() {
return value;
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package ru.tn.courses.vbogatyrev.v1.task2.enums;

public enum ColorEnum{
RED("красный"), GREEN("зеленый"), BLUE("синий");

private final String value;

ColorEnum(String value) {
this.value = value;
}

public String getValue() {
return value;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package ru.tn.courses.vbogatyrev.v1.task2.enums;

public enum DriveEnum {
FULL("полный"), FRONT("передний"), REAR("задний");

private final String value;

DriveEnum(String value) {
this.value = value;
}

public String getValue() {
return value;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package ru.tn.courses.vbogatyrev.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;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package ru.tn.courses.vbogatyrev.v1.task2.enums;

public enum TransmissionEnum {

MANUAL("механическая"), AUTOMATIC("автоматическая");

private final String value;

TransmissionEnum(String value) {
this.value = value;
}

public String getValue() {
return value;
}

}
Loading