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
72 changes: 69 additions & 3 deletions src/main/java/Main.java
Original file line number Diff line number Diff line change
@@ -1,8 +1,74 @@
import java.lang.NumberFormatException;
import java.util.Scanner;

public class Main {

private static final Scanner scanner = new Scanner(System.in);

private static String getRoubleWordWithCorrectEnding(int number) {
if (number % 100 > 9 && number % 100 < 20) {
return "рублей";
}
switch (number % 10) {
case 1:
return "рубль";
case 2:
case 3:
case 4:
return "рубля";
default:
return "рублей";
}
}

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

String amountOfUsersAsString;
int amountOfUsers;

while (true) {
amountOfUsersAsString = scanner.nextLine();
try {
amountOfUsers = Integer.parseInt(amountOfUsersAsString);
if (amountOfUsers > 1) {
break;
}
System.out.println("Должно быть как минимум два человека, чтобы разделить счет!\nПовторите ввод еще раз!");
} catch (NumberFormatException exception) {
System.out.println("Введен недопустимый параметр в качестве количества человек! Ожидалось целое число.\nПовторите ввод еще раз!");
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Можно поделить функцию main на несколько - считывание количества человек, считывание товаров, вывод результата

}
}

ProductCalculator calculator = new ProductCalculator();

double productPrice;
String productPriceAsString;
String productName;

System.out.println("Введите товар и его стоимость через пробел:");
while (!(productName = scanner.next()).equalsIgnoreCase("завершить")) {
productPriceAsString = scanner.nextLine();
try {
productPrice = Double.parseDouble(productPriceAsString);
if (productPrice < 0) {
System.out.println("У товара не может быть отрицательная цена!\nТовар не добавлен. Повторите ввод.");
continue;
}
calculator.addProduct(productName, productPrice);
System.out.println("Товар был успешно добавлен! Хотите добавить еще?\nЕсли да, то введите название товара и цену, иначе напишите слово \"завершить\":");
} catch (NumberFormatException exception) {
System.out.println("Не указана допустимая цена товара! Ожидалось вещественное число.\nТовар не был добавлен! Повторите корректный ввод заново.");
}
}

System.out.println("Добавленные товары:");
for (Product product : calculator.getProductsList()) {
System.out.println(product.getProductName());
}

double sumForEachToPay = calculator.getSumOfProducts() / amountOfUsers;
System.out.printf("Сумма, которую должен заплатить каждый: %.2f %s%n", sumForEachToPay, getRoubleWordWithCorrectEnding((int) sumForEachToPay));

}
}
19 changes: 19 additions & 0 deletions src/main/java/Product.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
public class Product {

String name;
double price;

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

public String getProductName() {
return name;
}

public double getProductPrice() {
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Метод не используется, а можно было бы выводить цену товара вместе с именем при завершении расчетов

return price;
}

}
25 changes: 25 additions & 0 deletions src/main/java/ProductCalculator.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import java.util.ArrayList;

public class ProductCalculator {

private ArrayList<Product> products = new ArrayList<>();
private double totalSumOfProducts = 0;

public void addProduct(String name, double price) {
products.add(new Product(name, price));
recalculateSum(price);
}

private void recalculateSum(double price) {
totalSumOfProducts += price;
}

public double getSumOfProducts() {
return totalSumOfProducts;
}

public ArrayList<Product> getProductsList() {
return products;
}

}