forked from Yandex-Practicum/Java-Module-Project-YP
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBillCalculator.java
More file actions
89 lines (82 loc) · 3.65 KB
/
BillCalculator.java
File metadata and controls
89 lines (82 loc) · 3.65 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.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class BillCalculator {
private static final DecimalFormat decimalFormat = new DecimalFormat("0.00");
private List<String> items;
private List<Double> prices;
private int numPeople;
public BillCalculator() {
items = new ArrayList<>();
prices = new ArrayList<>();
numPeople = 0;
}
public void start() {
enterNumPeople();
addItems();
displayResults();
}
private void enterNumPeople() {
Scanner scanner = new Scanner(System.in);
System.out.println("Введите количество людей:");
while (true) {
try {
numPeople = Integer.parseInt(scanner.nextLine());
if (numPeople == 1) {
System.out.println("Нет смысла считать и делить на 1 человека. Введите корректное количество гостей.");
} else if (numPeople < 1) {
System.out.println("Некорректное значение. Введите корректное количество гостей.");
} else {
break;
}
} catch (NumberFormatException e) {
System.out.println("Некорректное значение. Введите корректное количество гостей.");
}
}
}
private void addItems() {
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("Введите название товара или 'Завершить', чтобы завершить добавление товаров:");
String item = scanner.nextLine();
if (item.equalsIgnoreCase("завершить")) {
break;
}
double price;
while (true) {
try {
System.out.println("Введите стоимость товара (в формате рубли.копейки):");
price = Double.parseDouble(scanner.nextLine());
if (price <= 0) {
System.out.println("Некорректная стоимость товара. Введите положительное значение.");
} else {
break;
}
} catch (NumberFormatException e) {
System.out.println("Некорректная стоимость товара. Введите корректное значение.");
}
}
items.add(item);
prices.add(price);
System.out.println("Товар успешно добавлен.");
}
}
private void displayResults() {
System.out.println("\nДобавленные товары:");
for (int i = 0; i < items.size(); i++) {
System.out.println(items.get(i) + " - " + decimalFormat.format(prices.get(i)) + " рублей");
}
double totalAmount = 0;
for (double price : prices) {
totalAmount += price;
}
double perPersonAmount = totalAmount / numPeople;
System.out.println("\nСумма, которую должен заплатить каждый человек:");
System.out.println(decimalFormat.format(perPersonAmount) + " рубля");
}
public static void main(String[] args) {
BillCalculator calculator = new BillCalculator();
calculator.start();
}
}