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
57 changes: 57 additions & 0 deletions src/main/java/Calculator.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Scanner;

public class Calculator {
private final int numberOfPersons;
private final ArrayList<Product> productList = new ArrayList<>();
private final Formatter formatter;
private double totalPrice;

public Calculator(int numberOfPersons, Scanner scanner){
this.numberOfPersons = numberOfPersons;
this.formatter = new Formatter(scanner);
}

public void scanProducts(){
String inputValue, productName;
double productPrice;
totalPrice = 0;
while (true) {

System.out.println("Введите название товара или команду \"завершить\"");
inputValue = formatter.getString();

if (formatter.checkExitCommand(inputValue)) {
System.out.println("Ввод товаров завершен. Идет подсчет суммы, которую должен заплатить каждый человек");
break;
} else {
productName = inputValue;
productPrice = formatter.getProductPrice("Введите цену товара.", "Стоимость должна быть в формате рубли.копейки, например 10,45 или 11,40");
Product product = new Product(productName, productPrice);
productList.add(product);
totalPrice += productPrice;
String currencyName = formatter.getCurrencyDecline(productPrice);
System.out.println("Товар \"" + productName + "\" на сумму " + String.format("%.2f", productPrice) + " " + currencyName + " успешно добавлен в список!");
System.out.println("Хотите добавить еще один товар?");
}
}
}

public void showTotalReceipt() {
System.out.println("\nДобавленные товары:");
Iterator<Product> listIterator = productList.iterator();
while (listIterator.hasNext()){
Product product = listIterator.next();
System.out.println("\"" + product.getName() + "\" на сумму " + String.format("%.2f", product.getPrice()));
}

System.out.println("Общая сумма: " + String.format("%.2f", totalPrice));
double dividedPrice = formatter.getDividedPrice(totalPrice, numberOfPersons);
String currencyName = formatter.getCurrencyDecline(dividedPrice);
System.out.println("Каждый человек должен заплатить: " + String.format("%.2f", dividedPrice) + " " + currencyName);

}


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

public class Formatter {
private final Scanner scanner;
public Formatter(Scanner scanner) {
this.scanner = scanner;
}

public int scanNumberOfPersons() {

int numberOfPersons;
System.out.println("На скольких человек необходимо разделить счёт?");
String messageError = "Количество человек неверное, введите количество больше или равно 2";

while (true) {
if (!scanner.hasNextInt()) {
System.out.println(messageError);
getString();
} else {
numberOfPersons = scanner.nextInt();
if (numberOfPersons < 2){
System.out.println(messageError);
getString();
} else {
break;
}
}
}
getString(); // Очистка буфера ввода после Чтение числового значения из ввода
return numberOfPersons;
}

public String getString(){
return scanner.nextLine();
}

public double getProductPrice(String msgFirst, String msgRightPrice){

double price;
System.out.println(msgFirst + " " + msgRightPrice);
String msgErrorPrice = "Вы ввели некорректный формат стоимости.";

while (true) {
if (!scanner.hasNextDouble()){
System.out.println(msgErrorPrice + "\n" + msgRightPrice);
getString();
} else {
price = scanner.nextDouble();
price = Math.round(price * 100.0) / 100.0;
if (price <= 0.00){
System.out.println(msgErrorPrice + "\n" + msgRightPrice + " и больше 0");
} else {
break;
}
}
}
getString(); // Очистка буфера ввода после Чтение числового значения из ввода
return price;
}

public boolean checkExitCommand(String command) {
return command.equalsIgnoreCase("завершить");
}

public double getDividedPrice(double totalPrice, int numberOfPersons) {
double dividedPrice = totalPrice / numberOfPersons;
dividedPrice = Math.round(dividedPrice * 100.0) / 100.0; //Округление до 2 знаков после запятой
return dividedPrice;
}

public String getCurrencyDecline(double amount){

String currencyName;
int lastNumberBeforePoint = (int) (Math.floor(amount) % 10); // единицы числа
int nextToLastNumberBeforePoint = (int) (Math.floor(amount) / 10 % 10); // десятки числа
if (nextToLastNumberBeforePoint == 1) { // если число вышло от 10 до 19, то падеж будет как у 0 рублей
lastNumberBeforePoint = 0;
}

switch (lastNumberBeforePoint) {
case 1 -> currencyName = "рубль";
case 2, 3, 4 -> currencyName = "рубля";
case 5, 6, 7, 8, 9, 0 -> currencyName = "рублей";
default -> currencyName = "руб";
}

return currencyName;
}
}
13 changes: 12 additions & 1 deletion src/main/java/Main.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,17 @@
import java.util.Scanner;

public class Main {

public static void main(String[] args) {
System.out.println("Hello world!");
Scanner scanner = new Scanner(System.in);

System.out.println("Добро пожаловать в приложение по разделению счета!");
Formatter formatter = new Formatter(scanner);
int numberOfPersons = formatter.scanNumberOfPersons();
System.out.println("Количество человек: " + numberOfPersons);

Calculator calc = new Calculator(numberOfPersons, scanner);
calc.scanProducts();
calc.showTotalReceipt();
}
}
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 double price;

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

public String getName() {
return name;
}

public double getPrice() {
return price;
}
}