Skip to content
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
44 changes: 40 additions & 4 deletions src/main/java/Main.java
Original file line number Diff line number Diff line change
@@ -1,8 +1,44 @@
import java.util.InputMismatchException;
import java.util.Scanner;

public class Main {
public static Scanner scanner = new Scanner(System.in);

public static void main(String[] args) {
// ваш код начнется здесь
// вы не должны ограничиваться только классом Main и можете создавать свои классы по необходимости
System.out.println("Привет Мир");

System.out.println("Привет, на скольких человек необходимо разделить счёт?");
int peopleCount = getCountOfPeople();
ProductCalculator productCalculator = new ProductCalculator(peopleCount);
productCalculator.inputProducts();
}

public static int getCountOfPeople() {
int peopleCount = 0;

while (true) {
try {
peopleCount = scanner.nextInt();

if (isCorrectPeopleCount(peopleCount)) {
break;
}
} catch (InputMismatchException er) {
System.out.println("Некоректное значение, попробуйте другое");
scanner.nextLine();
}
}
return peopleCount;
}

public static boolean isCorrectPeopleCount(int peopleCount) {
if (peopleCount <= 0) {
System.out.println("Количество человек меньше 1. Это некорректное значение для подсчёта. Введите новое значение.");
return false;
} else if (peopleCount == 1) {
System.out.println("Количество человек, введённых пользователем равно 1. В этом случае нет смысла ничего считать и делить. Введите новое значение.");
return false;
} else {
return true;
}
}
}
}
17 changes: 17 additions & 0 deletions src/main/java/Product.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
public class Product {
private final String name;
private final float price;

Product(String name, float price) {
this.name = name;
this.price = price;
}

public String getName() {
return this.name;
}

public float getPrice() {
return this.price;
}
}
101 changes: 101 additions & 0 deletions src/main/java/ProductCalculator.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
import java.util.ArrayList;
import java.util.InputMismatchException;
import java.util.Scanner;

public class ProductCalculator {
private static final Scanner scanner = new Scanner(System.in);
private final ArrayList<Product> products = new ArrayList<>();
private float totalPriceOfAllProducts = 0.00f;
private final int peopleCount;


ProductCalculator(int peopleCount) {
this.peopleCount = peopleCount;
}

public void addProduct(Product product) {
this.products.add(product);
this.totalPriceOfAllProducts += product.getPrice();
}

public float getPricePerOnePerson() {
return totalPriceOfAllProducts / peopleCount;
}

public float getTotalAmountOfProducts() {
return this.totalPriceOfAllProducts;
}

public void showAllProducts() {
System.out.println("Список продуктов:");
for (int i = 0; i < products.size(); i++) {
System.out.printf("%d) Название: \"%s\", стоимость: %.2f %s. \n",
i + 1,
products.get(i).getName(),
products.get(i).getPrice(),
getCorrectEnding(products.get(i).getPrice()));
}
}

public void showResult() {
showAllProducts();
System.out.printf("Конечная стоимость всего товара: %.2f %s \n", getTotalAmountOfProducts(), getCorrectEnding(getTotalAmountOfProducts()));
System.out.printf("Каждый человек должен будет заплатить: %.2f %s", getPricePerOnePerson(), getCorrectEnding(getPricePerOnePerson()));
}

private String getCorrectEnding(float rubles) {

float roundedOffRubles = (float) Math.floor(rubles);

if (roundedOffRubles == 1.00f) {
return "рубль";
} else if (roundedOffRubles > 1 && roundedOffRubles < 5) {
return "рубля";
} else {
return "рублей";
}
}

public void inputProducts() {
String productName;
float productPrice;


while (true) {
System.out.print("Введите название товара: ");
productName = scanner.next();

System.out.println("Введите стоимость товара стоимость в формате: \"'рубли.копейки' [10.45, 11.40]\"");
try {
productPrice = scanner.nextFloat();
} catch (InputMismatchException er) {
System.out.println("Цена товара некорректна, введите товар заново.");
scanner.nextLine();
continue;
}

if (productPrice <= 0.0f) {
System.out.println("Цена товара некорректна, введите товар заново.");
continue;
}

Product product = new Product(productName, productPrice);
addProduct(product);

System.out.printf("Вы успешно довавила товар \"%s\" \n", productName);

System.out.printf("Предварительная стоимость всех товаров = %.2f %s\n", getTotalAmountOfProducts(), getCorrectEnding(getTotalAmountOfProducts()));


System.out.println("\nВедите \"Завершить\", если добавили всё нужные товары");
System.out.println("Добавить ещё товар?");

String answer = scanner.next();

if (answer.equalsIgnoreCase("завершить")) {
showResult();
break;
}
}
}
}