Repository navigation
Expand file tree
/
Copy pathCountDivisionCalculator.java
More file actions
89 lines (71 loc) · 2.85 KB
/
Copy pathCountDivisionCalculator.java
File metadata and controls
89 lines (71 loc) · 2.85 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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
import java.util.ArrayList;
import java.util.Scanner;
public class CountDivisionCalculator {
private Scanner scanner;
private ArrayList<Item> itemList;
Formatter formatter = new Formatter();
public CountDivisionCalculator() {
scanner = new Scanner(System.in);;
itemList = new ArrayList<>();
}
void calculate(int howManyPeople) {
createItems();
}
private void createItems() {
while (true) {
System.out.print("Введите наименование товара: ");
String name = scanner.nextLine();
double price = readPrice();
itemList.add(new Item(name, price));
System.out.println("Товар " + name + " успешно добавлен.");
double totalSum = calculateTotal();
String padej = formatter.getPadej(totalSum);
System.out.printf("Общая сумма товаров в корзине: %.2f %s%n", totalSum, padej);
if (!continueAdd()) {
break;
}
}
}
private double readPrice() {
while (true) {
System.out.print("Введите стоимость товара в формате рубли.копейки: ");
String input = scanner.nextLine();
String[] twoFloat = input.split("\\.");
if (twoFloat.length == 2 && twoFloat[1].length() <= 2) {
if (isValidDouble(twoFloat[0] + "." + twoFloat[1])) {
double price = Double.parseDouble(input);
if (price < 0) {
System.out.println("Цена не может быть отрицательной.");
continue;
}
return price;
} else {
System.out.println("Неверный формат ввода.");
}
} else {
System.out.println("Неверный формат ввода.");
}
}
}
private boolean isValidDouble(String input) {
return input.matches("-?\\d+(\\.\\d+)?");
}
private boolean continueAdd() {
System.out.print("Для завершения, введите \"завершить\". Для продолжения, введите любой текст: ");
String input = scanner.nextLine().trim().toLowerCase();
return !input.equals("завершить");
}
double calculateTotal() {
double totalAmount = 0.0;
for (Item item : itemList) {
totalAmount += item.getPrice();
}
return totalAmount;
}
void itemPrint() {
System.out.println("Добавленные товары:");
for (Item item : itemList) {
System.out.printf("%s %.2f%n", item.getName(), item.getPrice());
}
}
}