This repository was archived by the owner on Dec 23, 2024. It is now read-only.
Repository navigation
Expand file tree
/
Copy pathCalculator.java
More file actions
96 lines (90 loc) · 3.55 KB
/
Copy pathCalculator.java
File metadata and controls
96 lines (90 loc) · 3.55 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
90
91
92
93
94
95
96
import java.util.ArrayList;
import java.util.Locale;
import java.util.Scanner;
public class Calculator {
private final Scanner scanner = new Scanner(System.in).useLocale(Locale.ENGLISH);
private int guestsCount;
private final ArrayList<Product> products = new ArrayList<>();
public void resolveGuestsCount() {
System.out.println("На скольких человек необходимо разделить счёт?");
while (true) {
try {
int count = scanner.nextInt();
if (count > 1) {
guestsCount = count;
break;
}
} catch (Exception e) {
scanner.next();
}
System.out.println("Введено неверное значение, попробуйте еще раз");
}
}
public void resolveProducts() {
while (true) {
System.out.println("Введите название товара");
String productName = scanner.next();
double productPrice = resolvePrice();
products.add(new Product(productName, productPrice));
System.out.println("Товар успешно добавлен");
System.out.println("Введите любой символ, чтобы добавить еще один товар или введите Завершить");
if (scanner.next().equalsIgnoreCase("завершить")) {
break;
}
}
}
public void proceedTotals() {
StringBuffer productsTotal = new StringBuffer();
float sum = 0f;
int productsLastIndex = products.size() - 1;
for (int i = 0; i <= productsLastIndex; i++) {
Product product = products.get(i);
productsTotal.append(product.name);
if (i != productsLastIndex) {
productsTotal.append("\n");
}
sum += product.price;
}
System.out.println("Добавленные товары:");
System.out.println(productsTotal);
System.out.println(formatGuestBill(sum / guestsCount));
}
private double resolvePrice() {
double validatedPrice;
while (true) {
System.out.println("Введите стоимость товара в формате рубли.копейки");
double price = 0.0;
try {
String priceInput = scanner.next();
int fractionSize = priceInput.split("\\.")[1].length();
if (fractionSize == 2) {
price = Double.parseDouble(priceInput);
}
} catch (Exception e) {
scanner.next();
}
if (price > 0) {
validatedPrice = price;
break;
} else {
System.out.println("Введено некорректное значение");
}
}
return validatedPrice;
}
private String formatGuestBill(float amount) {
int amountLastDigit = ((int) amount) % 10;
int amountTenth = ((int) amount) % 100;
String currency;
if (amountTenth > 10 && amountTenth < 15) {
currency = "рублей";
} else if (amountLastDigit == 1) {
currency = "рубль";
} else if (amountLastDigit < 5) {
currency = "рубля";
} else {
currency = "рублей";
}
return String.format(Locale.ENGLISH, "%.2f ".concat(currency), amount);
}
}