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
81 lines (75 loc) · 3.25 KB
/
Calculator.java
File metadata and controls
81 lines (75 loc) · 3.25 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
import java.util.ArrayList;
import java.util.InputMismatchException;
import java.util.Scanner;
public class Calculator {
private int numberOfGuests;
private double totalCost;
private Scanner scanner;
ArrayList<String> itemNames = new ArrayList<String>();
public Calculator() {
scanner = new Scanner(System.in);
}
public void run() {
getNumberOfGuests();
addItemsToCalculator();
showResults();
}
private void getNumberOfGuests() {
System.out.println("Введите количество гостей");
while (true) {
try {
numberOfGuests = scanner.nextInt();
if (numberOfGuests <= 1) {
System.out.println("Некорректное количество гостей");
} else {
break;
}
} catch (InputMismatchException e) {
System.out.println("Некорректный ввод. Введите число");
scanner.next();
}
}
}
private void addItemsToCalculator() {
System.out.println("Добавление товаров для подсчета.");
while (true) {
System.out.println("Введите название товара или Введите 'Завершить', чтобы закончить ввод.");
String itemName = scanner.next();
if (itemName.equalsIgnoreCase("Завершить")) {
break;
}
System.out.println("Введите стоимость товара:");
while (true) {
try {
double itemCost = scanner.nextDouble();
if (itemCost <= 0) {
System.out.println("Некорректный ввод.Стоимость не может быть отрицательной, либо равняться нулю.");
} else {
itemNames.add(itemName);
totalCost += itemCost;
System.out.println("Товар '" + itemName + "' успешно добавлен");
break;
}
} catch (InputMismatchException e) {
System.out.println("Некорректный ввод.Введите число");
scanner.next();
}
}
}
}
private void showResults() {
System.out.println("Добавленые товары:");
for (String name : itemNames) {
System.out.println(name);
}
System.out.println("Общая стоимость:" + totalCost);
int costPerGuest = (int) (totalCost / numberOfGuests);
String currency = "рублей";
if (costPerGuest % 10 == 1 && costPerGuest % 100 != 11) {
currency = "рубль";
} else if (costPerGuest % 10 >= 2 && costPerGuest % 10 <= 4 && (costPerGuest % 100 < 10 || costPerGuest % 100 >= 20)) {
currency = "рубля";
}
System.out.println("Стоимость на каждого гостя: " + String.format("%.2f", totalCost / numberOfGuests) + " " + currency);
}
}