forked from Yandex-Practicum/Java-Module-Project-YP
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMain.java
More file actions
85 lines (76 loc) · 3.38 KB
/
Main.java
File metadata and controls
85 lines (76 loc) · 3.38 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
import java.util.Scanner;
public class Main {
private static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("Введите на сколько человек нужно разделить счёт:");
int peopleAmount = readPeopleAmount();
String command = "";
final String endCommand = "завершить";
while (!endCommand.equalsIgnoreCase(command)) {
ProductCalculator.addProduct(readProduct());
System.out.println("Если хотите завершить добавление товаров, то введите слово " +
"\"Завершить\".\n В противном случае введите, что угодно.");
command = scanner.nextLine();
}
System.out.println("Добавленные товары:");
ProductCalculator.printAllProducts();
printAveragePrice(ProductCalculator.getTotalCost(), peopleAmount);
}
public static int readPeopleAmount() {
int amount = 0;
final int minPeopleAmount = 1;
while (true) {
String input = scanner.nextLine();
try {
amount = Integer.parseInt(input);
if (amount >= minPeopleAmount) {
break;
}
} catch (NumberFormatException | NullPointerException ignored) {
}
System.out.println("Введите корректное количество человек:");
}
return amount;
}
public static Product readProduct() {
System.out.println("Введите название товара, который хотите добавить:");
String productName = scanner.nextLine();
System.out.println("Введите стоимость этого товара:");
double price = 0.;
while (true) {
String input = scanner.nextLine();
try {
price = Double.parseDouble(input);
if (price > 0.) {
break;
}
} catch (NumberFormatException | NullPointerException ignored) {
}
System.out.println("Введите корректное значение цены товара '" + productName + "':");
}
return new Product(productName, price);
}
public static void printAveragePrice(double totalCost, int peopleAmount) {
double avgPrice = totalCost / peopleAmount;
System.out.println("\nКаждый должен заплатить по:");
String rubleWord = getRubleWordByNum(avgPrice);
System.out.println(String.format("%.2f %s", avgPrice, rubleWord));
}
public static String getRubleWordByNum(double rubles) {
int roundedRubles = ((int) Math.floor(rubles));
final int divHundredReminder = roundedRubles % 100;
final int divTenReminder = roundedRubles % 10;
if (!InRange(divHundredReminder, 11, 14)) {
if (InRange(divTenReminder, 2, 4)) {
return "рубля";
}
if (divTenReminder == 1) {
return "рубль";
}
}
return "рублей";
}
public static boolean InRange(int value, int lower, int upper) {
return ((lower <= value) && (value <= upper));
}
}