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
18 changes: 18 additions & 0 deletions src/main/java/Calculator.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
public class Calculator {
int countPeople;
double currentTotalAmount = 0;
String products = "";

Calculator(int countPeople) {
this.countPeople = countPeople;
}

void addProductCost(Product product) {
products += product.name + "\r\n";
currentTotalAmount += product.cost;
}

double getEachFriendAmount() {
return currentTotalAmount / countPeople;
}
}
92 changes: 89 additions & 3 deletions src/main/java/Main.java
Original file line number Diff line number Diff line change
@@ -1,8 +1,94 @@
import java.util.Scanner;

public class Main {

public static Calculator initializeCalculator(Scanner inputScanner) {
int countFriends = -1;
// Получение количества друзей.
while (countFriends <= 1) {
System.out.println("На скольких человек необходимо разделить счёт?");

if (inputScanner.hasNextInt()) {
countFriends = inputScanner.nextInt();

} else {
System.out.println("[Ошибка] Необходимо ввести целочисленное количество друзей.");
inputScanner.next();
continue;

}
if (countFriends == 1) {
System.out.println("[Ошибка] Нет смысла ничего считать и делить.");

} else if (countFriends < 1) {
System.out.println("[Ошибка] " + countFriends + " - это некорректное значение для подсчёта.");

}
}

// Инициализация калькулятора в зависимости от количества друзей.
return new Calculator(countFriends);
}

// Добавление товаров в калькулятор.
public static void addProductsToCalculator(Scanner inputScanner, Calculator calculator) {
while (true) {
System.out.println("Введите название товара:");
String product = inputScanner.next();

System.out.println("Введите цену товара в формате рубли.копейки:");
while (true) {
if (inputScanner.hasNextDouble()) {
double productCost = inputScanner.nextDouble();
if (productCost < 0) {
System.out.println("[Ошибка] Введите корректную цену товара: цена не может быть отрицательной.");
} else {
calculator.addProductCost(new Product(product, productCost));
System.out.println("Товар успешно добавлен в корзину.");
break;
}
} else {
inputScanner.next();
System.out.println("[Ошибка] Введите корректную цену товара в формате: рубли.копейки");
}
}

System.out.println("Хотите ли добавить ещё один товар? завершить/что-либо");
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

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

public static void printEachFriendAmount(Calculator calculator) {
double eachFriendAmount = calculator.getEachFriendAmount();
String rubles = "";
switch ((int)eachFriendAmount % 10) {
case 1:
rubles = "рубль";
break;
case 2:
case 3:
case 4:
rubles = "рубля";
break;
case 0:
case 5:
case 6:
case 7:
case 8:
case 9:
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Можно поставить вместо перечисления оставшихся вариантов (0, 5, ..., 9) просто ветку default

rubles = "рублей";
break;
}
System.out.println("Добавленные товары:\r\n" + calculator.products + String.format("%.2f", eachFriendAmount) + " " + rubles);
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Можно чуть расписать для пользователя, что за сумму выводишь, например "Каждый из друзей должен заплатить ..."

}

public static void main(String[] args) {
// ваш код начнется здесь
// вы не должны ограничиваться только классом Main и можете создавать свои классы по необходимости
System.out.println("Привет Мир");
Scanner inputScanner = new Scanner(System.in);
Calculator calculator = initializeCalculator(inputScanner);
addProductsToCalculator(inputScanner, calculator);
printEachFriendAmount(calculator);
}
}
9 changes: 9 additions & 0 deletions src/main/java/Product.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
public class Product {
String name;
double cost;

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