forked from Yandex-Practicum/Java-Module-Project-YP
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCalculator.java
More file actions
55 lines (49 loc) · 2.42 KB
/
Calculator.java
File metadata and controls
55 lines (49 loc) · 2.42 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import java.util.ArrayList;
import java.util.Scanner;
public class Calculator {
public int personCount;
public double totalPriceSum;
public double dividedSum;
public ArrayList<Product> products = new ArrayList<>();
private final Scanner scanner = new Scanner(System.in);
Calculator(int personCount){
this.personCount = personCount;
}
public void addToCart(){
while (true) {
System.out.println("\nВведите название товара:");
String inputName = scanner.nextLine();
if(inputName.trim().equalsIgnoreCase("завершить")) {
break;
}
System.out.println("Введите его стоимость в формате 'рубли.копейки':");
while (true) {
String inputPrice = scanner.nextLine();
try
{
double price = Double.parseDouble(inputPrice);
if(price < 0) {
System.out.println("Стоимость не может быть отрицательной. Повторите ввод:");
} else {
System.out.printf("Принято: товар '%s' с ценой %.2f успешно добавлен в корзину!%n", inputName, price);
totalPriceSum += price;
products.add(new Product(inputName, price));
System.out.println("Если хотите добавить еще товары, продолжайте ввод, иначе введите 'Завершить'");
break;
}
}
catch (NumberFormatException e)
{
System.out.println("Неверный формат: введите стоимость товара в формате 'рубли.копейки':");
}
}
}
}
public String calculate() {
dividedSum = totalPriceSum / personCount;
// определяем, с каким окончанием нужно закончить фразу: "рубль/рубля/рублей"
Formatter formatter = new Formatter();
String phraseEnd = formatter.getPhraseEnd(dividedSum);
return String.format("Все должны заплатить по %.2f %s", dividedSum, phraseEnd);
}
}