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
3 changes: 3 additions & 0 deletions .idea/.gitignore

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions .idea/compiler.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

18 changes: 18 additions & 0 deletions .idea/gradle.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

10 changes: 10 additions & 0 deletions .idea/misc.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions .idea/vcs.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
# Bill Calculator
Учебное приложение, направленое на совершенствование навыков работы с языком программирования Java.
80 changes: 80 additions & 0 deletions src/main/java/Calculator.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
import java.util.ArrayList;
import java.util.List;

public class Calculator {
/* Этот класс выполняет обработку входных данных после заказа. Расчитывает стоимость на каждого
человека и выводит данные на консоль
*/

private final int numberOfVisitors;
private final List<Product> listOfProducts;

public Calculator(int numberOfVisitors) {
this.numberOfVisitors = numberOfVisitors;
this.listOfProducts = new ArrayList<>();

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Можно перенести инициализацию в место объявления

}

public List<Product> getListOfProducts() {
return this.listOfProducts;
}

public int getNumberOfVisitors() {
return this.numberOfVisitors;
}

// Добавляет объект класса Product в listOfProducts
public void addProductToList(Product product) {
listOfProducts.add(product);
}

@Override
public String toString() {
return "Количество посетителей: " + this.numberOfVisitors + "\n" +
"Список продуктов: " + this.listOfProducts;
}

// Расчитывает стоимость по счету на каждого посетителя
private double calculate() {
double totalValue = 0;
for (Product product:listOfProducts) {
totalValue += product.getValue();
}
return totalValue / this.numberOfVisitors;
}

// Возвращает слово "Рубль" с правильным окончанием в зависимости от значения
private String getRightWord(double value) {
String[] vars = {"рубль", "рубля", "рублей"};
int valueToInt = (int) value;
if ((valueToInt / 10) % 10 == 1) {
return vars[2];
} else {
switch (valueToInt % 10) {
case 1:
return vars[0];

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Использование массива строк интересный вариант, но получается, что в коде стороннему разработчику с первого взгляда непонятно, что значит vars[0]. Обычные переменные или константы могут быть более информативны

case 2:
case 3:
case 4:
return vars[1];
default:
return vars[2];
}
}
}

// Выводит итоговые результаты
public void printResults() {
System.out.println("Добавленные товары:");
for (Product product:listOfProducts) {
System.out.println(product.getName() + " " + String.format("%.2f", product.getValue()) +
" " + getRightWord(product.getValue()));
}

double valuePerPerson = this.calculate();

System.out.println("Итого:");
System.out.println("Колличество персон: " + this.getNumberOfVisitors());
System.out.println("Стоимость по чеку на каждую персону составляет по: "
+ String.format("%.2f", valuePerPerson) + " " + getRightWord(valuePerPerson));
}
}
84 changes: 81 additions & 3 deletions src/main/java/Main.java
Original file line number Diff line number Diff line change
@@ -1,8 +1,86 @@
import java.util.Scanner;
import java.util.regex.Pattern;

public class Main {
// количество посетителей
static int numberOfVisitors;
// объект типа Calculator
static Calculator calculator;

public static void main(String[] args) {
// ваш код начнется здесь
// вы не должны ограничиваться только классом Main и можете создавать свои классы по необходимости
System.out.println("Привет Мир");
numberOfVisitors = getNumberOfVisitors();
calculator = new Calculator(numberOfVisitors);
requestProductFromUser();

if (calculator.getListOfProducts().isEmpty()) {
System.out.println("Ничего не было заказано...");
} else {
calculator.printResults();
}
}

/* спрашивает у пользователя, на скольких человек необходимо разделить счёт
и возвращает это значение
*/
private static int getNumberOfVisitors() {
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("На скольких человек нужно разделить счет?");
String response = scanner.next();
if (isNumeric(response)) {
int intValue = Integer.parseInt(response);
if (intValue <= 1) {
System.out.println("Значение должно быть больше 1...");
} else {
return intValue;
}
} else {
System.out.println("Введите корректное значение...");
}
}
}

// Проверяет, является ли введеное пользователем значение целочисленным числом - true, иначе - false
private static boolean isNumeric(String string) {
String numericPattern = "\\d+";
return Pattern.matches(numericPattern, string);
}

// Проверяет, является ли введеное пользователем значение цислом с дробной частью - true, иначе - false
private static boolean isDoubleNumeric(String string) {
String decimalPattern = "([0-9]*)\\.([0-9]*)";
return Pattern.matches(decimalPattern, string);
}

/* Запрашивает наименование и стоимость продукта у пользователя и добавляет объекты
класса Product в объект calculator класса Calculator, пока пользователь не введет команду
"Завершить"
*/
private static void requestProductFromUser() {
Scanner scanner = new Scanner(System.in);
String nameOfProduct;
double value;

while (true) {
System.out.println("Введите, пожалуйста, название товара. (Чтобы завершить процесс, введите \"Завершить\")");
String response = scanner.next();
if (response.equalsIgnoreCase("завершить")) {
return;
} else {
nameOfProduct = response;
while (true) {
System.out.println("Введите, пожалуйста, стоимость товара в формате XX.YY (где ХХ - рубли, YY - копейки)...");
response = scanner.next();
if (isDoubleNumeric(response)) {
value = Double.parseDouble(response);
break;
} else {
System.out.println("Введите корректное значение...");
}
}
calculator.addProductToList(new Product(nameOfProduct, value));
System.out.println("Продукт успешно добавлен в калькулятор");
}
}
}
}
28 changes: 28 additions & 0 deletions src/main/java/Product.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
public class Product {
/* На основе этого класса будут созданы объекты Product, которые будут служить
исходным материалом для расчета общей стоимости заказа
*/

// наименование товара
private final String name;
// стоимость товара
private final double value;

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

public String getName() {
return this.name;
}

public double getValue() {
return this.value;
}

@Override
public String toString() {
return "Наименование: " + this.name + ", Стоимость: " + this.value;
}
}