-
Notifications
You must be signed in to change notification settings - Fork 218
Expand file tree
/
Copy pathCalculator.java
More file actions
75 lines (62 loc) · 4.13 KB
/
Calculator.java
File metadata and controls
75 lines (62 loc) · 4.13 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
import java.util.Scanner;
public class Calculator {
static Scanner scanner = new Scanner(System.in);
static String userInput = null;
static String productName;
static String allProductsList = "Добавленные товары:";
static float productCost = 0.0F;
static float allProductsCost = 0.0F;
static float personalAmount = 0.0F;
static String checkedNumber = null;
static void printResult(int numberOfGuests) {
while (!"ЗАВЕРШИТЬ".equalsIgnoreCase(userInput)) {// цикл продолжается до ввода слова "заврешить" игнорируя регистр букв
System.out.println("Введите название товара и его цену.\nТовар: ");
productName = scanner.next();
allProductsList = allProductsList + "\n" + productName;
System.out.println("Введите стоимость: ");
checkedNumber = scanner.next();
while (true) {// цикл проверяет число ли ввёл пользователь и не является ли оно отрицательным
if (!isItaNumber(checkedNumber)) {
System.out.println("Бип, ошибка. Это не число, либо вы в качестве делителя используете запятую вместо точки.\nПопробуйте ещё раз. Введите цену: ");
checkedNumber = scanner.next();
} else if (!isItPositive(productCost = Float.parseFloat(checkedNumber))) {
System.out.println("Бип, ошибка. Цена не может быть отрицательной!\nПопробуйте ещё раз. Введите цену: ");
checkedNumber = scanner.next();
} else {
break;
}
}
allProductsCost += productCost;
System.out.println("Вы успешно добавили " + productName + " за " + String.format("%.2f", productCost) + " рублей.\nЕсли хотите завершить, наберите \"Завершить\" и нажмите \"enter\".\nЕсли хотите добавить ещё один товар, введите любой символ или слово и нажмите \"enter\".");
userInput = scanner.next();
}
String rubleEnding = getRubleEnding((int) Math.floor(allProductsCost)); // выясняем верное окончание слова "рубль" для общей суммы заказа
System.out.println(allProductsList + "\nОбщая сумма: " + String.format("%.2f", allProductsCost) + rubleEnding);
personalAmount = allProductsCost / numberOfGuests;
String personalRubleEnding = getRubleEnding((int) Math.floor(personalAmount));// выясняем верное окончание слова "рубль" для суммы отдельного гостя
System.out.println("Каждому гостю необходимо заплатить: " + String.format("%.2f", personalAmount) + personalRubleEnding);
}
private static boolean isItPositive(float productCost) {// проверяем не является ли число отрицательным
return productCost >= 0;
}
private static boolean isItaNumber(String checkedNumber) {// проверяем число ли ввёл пользователь
return checkedNumber.matches("-?\\d+(\\.\\d+)?");
}
public static String getRubleEnding(int wholeRubles) {// подбираем правльное окончание слову "рубль"
int preLastDigit = wholeRubles % 100 / 10;
if (preLastDigit == 1) {
return " рублей.";
} else {
switch (wholeRubles % 10) {
case 1:
return " рубль.";
case 2:
case 3:
case 4:
return " рубля.";
default:
return " рублей.";
}
}
}
}