Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
78 changes: 78 additions & 0 deletions src/main/java/Calculator.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
import java.util.ArrayList;
import java.util.InputMismatchException;
import java.util.Scanner;

public class Calculator {
int guests;
double sum;
ArrayList<Product> productsList = new ArrayList<>();

Calculator(int guests) {
this.guests = guests;
}

static int getAmountOfGuests(Scanner scanner) {
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

старайся использовать нестатические функции, так так статические функции постоянно висят в памяти и соответственно занимают её, чего стоит избегать, иначе на устройстве может банально закончится память и твоё приложение закроется с ошибкой

int guests;
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

по возможности избегай ситуаций, когда твоя внутренняя переменная называется точно так же, как и внешняя, иначе очень легко могут возникнуть ошибки, когда нужно было присвоить значение внешней, а присвоилось внутренней и наоборот

System.out.println("Введите количество гостей:");
while (true) {
try {
guests = scanner.nextInt();
} catch (InputMismatchException e) {
System.out.println("Неверный тип вводимого значения");
// Очистка символа новой строки из буфера ввода
scanner.nextLine();
continue;
}
if (guests > 1) break;
else System.out.println("Некорректное значение для подсчёта");
}
return guests;
}

double addProductAndGetSum(Calculator calculator, Scanner scanner) {
double sum = 0;
// Очистка символа новой строки из буфера ввода
scanner.nextLine();
while (true) {
System.out.println("Введите название товара:");
String name = scanner.nextLine();

double price;
do {
System.out.println("Введите стоимость товара:");
try {
price = scanner.nextDouble();
} catch (InputMismatchException e) {
System.out.println("Неверный тип вводимого значения");
// Очистка символа новой строки из буфера ввода
scanner.nextLine();
continue;
}
break;
} while (true);
Product product = new Product(name, price);
calculator.productsList.add(product);
sum += price;
System.out.println(String.format("Товар %s успешно добавлен", name));
System.out.println("Хотите ли добавить еще один товар?");
// Очистка символа новой строки из буфера ввода
scanner.nextLine();
String word = scanner.nextLine();
if ("завершить".equalsIgnoreCase(word)) break;
}
return sum;
}

void printAllProducts(Calculator calculator) {
System.out.println("Добавленные товары:");
for (Product element : calculator.productsList) {
System.out.println(element.name);
}
}

void printResultingSum(Calculator calculator) {
double resultSum = calculator.sum / calculator.guests;
Formatter formatter = new Formatter();
System.out.println(String.format("%.2f %s", resultSum, formatter.getDeclension(resultSum)));
}
}
25 changes: 25 additions & 0 deletions src/main/java/Formatter.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
public class Formatter {
String getDeclension(double price) {
int resultSumIntDiv10 = ((int) price) % 10;
String rub = "";
switch (resultSumIntDiv10) {
case 1:
rub = "рубль";
break;
case 2:
case 3:
case 4:
rub = "рубля";
break;
case 5:
case 6:
case 7:
case 8:
case 9:
case 0:
rub = "рублей";
break;
}
return rub;
}
}
9 changes: 8 additions & 1 deletion src/main/java/Main.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,13 @@
import java.util.Scanner;

public class Main {
public static void main(String[] args) {
System.out.println("Hello world!");
Scanner scanner = new Scanner(System.in);
int guests = Calculator.getAmountOfGuests(scanner);
Calculator calc = new Calculator(guests);
calc.sum = calc.addProductAndGetSum(calc, scanner);
scanner.close();
calc.printAllProducts(calc);
calc.printResultingSum(calc);
}
}
9 changes: 9 additions & 0 deletions src/main/java/Product.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
public class Product {
String name;
double price;

Product(String name, double price) {
this.name = name;
this.price = price;
}
}