Repository navigation
Expand file tree
/
Copy pathMain.java
More file actions
203 lines (182 loc) · 9.69 KB
/
Copy pathMain.java
File metadata and controls
203 lines (182 loc) · 9.69 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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
import java.lang.String;
import java.lang.System;
import java.util.ArrayList;
import java.util.Scanner;
import java.lang.Double;
public class Main {
private static final Scanner scanner = new Scanner(System.in);
public static double sum = 0;
public static void main(String[] args) {
ProcessCreateProduct goods = new ProcessCreateProduct();
goods.calculateAndPrint();
}//main
//******************************************************************************************
/*класс ввода количества человек,
* содержит единственный метод enterPerson()*/
static class NumPerson {
int person = 0;
public int enterPerson(){
System.out.println("Введите количество человек (целое, больше 1): ");
//данные, оставшиеся в Scanner после считывания
String remainedData ="";
while (true){
if (scanner.hasNextInt()){
person = scanner.nextInt();
// Проверяем, остались ли данные в scanner
if (scanner.hasNextLine()) {
remainedData = scanner.nextLine();
if (remainedData.length()>1) {
System.out.println("Введите только число! Введите еще раз:");
continue;
}
}
if (person<= 1){
System.out.println("Число должно быть больше 1! Введите еще раз: ");
} else {
return person;
}
} else if (scanner.hasNextDouble()) {
System.out.println("Число должно быть целым! Введите еще раз: ");
scanner.next();
} else if (scanner.hasNextLine()){ //если ввод нач с букв, заканчивается целым числом
System.out.println("Введите только число! Введите еще раз: ");
scanner.nextLine();
}
}
}//enterPerson
}//NumPerson
//**********************************************************************
/*Основной класс работы с товаром
* Содержит след методы:
* createProduct() - ввод товаров, цены, форматир рублей и проверок ввода
* getPrice() - проверка правильности введеной цены
* calculateAndPrint() - метод, содержащий всю структуру программы,
* от ввода данных, подсчета суммы, печати товаров и стоимости */
static class ProcessCreateProduct{
ArrayList<Product>productsList = new ArrayList<>();
ArrayList createProduct(){
String newName = "";
double newPrice = 0;
String newRubles = "";
while (true){
System.out.println("Введите название товара: ");
newName = scanner.nextLine();
newName = newName.trim();
//проверка на пустую строку или строку из пробелов
if (newName.isBlank()){
System.out.println("Вы не можете ввести пустое название товара! ");
continue;
}
boolean flPutProduct = false; //флаг уже положенного товара
//Если уже есть данный товар в списке
if (!productsList.isEmpty()){
//ищем его в списке
for (Product item: productsList){
if (item.name.equalsIgnoreCase(newName)){
//кладем в список вместе с ценой
productsList.add(item);
System.out.println("Товар "+ item.name + " успешно добавлен в корзину. Стоимость товара " + item.price + " " + item.rubles);
sum+= item.price;
flPutProduct = true;
break;
}
}
}
if (!flPutProduct) {
System.out.println("Введите цену товара в рублях (формат рр,кк): ");
newPrice = getPrice();
//тк склонение слово рубль - отдельный класс
FormatRubles format = new FormatRubles();
newRubles = format.formatRubles(newPrice);
//Товар прошел все проверки
//создаем объект товара, кладем в список
Product newProduct = new Product(newName,newPrice,newRubles);
productsList.add(newProduct);
System.out.println("Товар "+ newProduct.name + " успешно добавлен в корзину");
sum+= newProduct.price;
}
System.out.println("Хотите добавить следующий товар?");
System.out.println("Для прекращения ввода введите команду: Завершить ");
System.out.println("Для продолжения работы нажмите любую клавишу ");
String command = scanner.nextLine();
if (command.equalsIgnoreCase("Завершить")){
return productsList;
}
}//while
}//createProduct
private double getPrice(){
double number = 0;
//данные, оставшиеся в Scanner после считывания
String remainedData ="";
while (true){
if (scanner.hasNextDouble()){
number = scanner.nextDouble();
// Проверяем, остались ли данные в scanner
if (scanner.hasNextLine()) {
remainedData = scanner.nextLine();
if (remainedData.length()>1) {
System.out.println("Введите только число в формате: рубли,копейки! Введите еще раз:");
continue;
}
}
if (number <= 0){
System.out.println("Цена должна быть больше 0! Введите еще раз: ");
} else return number;
} else if (scanner.hasNextLine()){ //если ввод нач с букв, заканчивается числом
System.out.println("Введите только число в формате: рубли,копейки! Введите еще раз: ");
scanner.nextLine();
}
}
}//getPrice
void calculateAndPrint(){
NumPerson countPerson = new NumPerson();
int number = countPerson.enterPerson();
ArrayList<Product> list = new ArrayList<>(createProduct());
System.out.println("Добавленные товары: ");
String message = "Товар: %s\tцена: %.2f %s";
for (int i = 0; i<list.size();i++) {
System.out.println(String.format(message,list.get(i).name,list.get(i).price,list.get(i).rubles));
}
double amount = (double) (sum/number);
FormatRubles format = new FormatRubles();
String rubl = format.formatRubles(amount);
System.out.println(String.format("Общая цена: %.2f", sum));
System.out.println(String.format("Каждый человек должен заплатить: %.2f %s",amount,rubl));
}//calculateAndPrint
}//ProcessCreateProduct
//********************************************************************
/*Класс склонения слова "рубль"
* содержит метод formatRubles(double price)*/
static class FormatRubles{
public String formatRubles(double price){
//отбросим дробную часть
int digit = Double.valueOf(price).intValue();
if(((digit % 100)>=11)&&((digit % 100)<=14)){
return " рублей";
} else {
switch (digit % 10) {
case 1:
return " рубль";
case 2:
case 3:
case 4:
return " рубля";
default:
return " рублей";
}
}
}
}//FormatRubles
//****************************************************************
/*Класс структуры товара, который добавляем в список*/
static class Product {
String name; //название товара
double price; //цена
String rubles; //формат валюты
public Product(String name,double price, String rubles){
this.name = name;
this.price = price;
this.rubles = rubles;
}
}//Product
}