Repository navigation
Проектная работа № 1 (правка после 1 ревью) #92
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: master
Are you sure you want to change the base?
Changes from all commits
2dda24e
f7ea4b9
fd519ca
577c86f
823d7e9
ab02f4b
2b2d0e0
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,2 @@ | ||
| # Bill 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<>(); | ||
| } | ||
|
|
||
| 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]; | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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)); | ||
| } | ||
| } | ||
| 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("Продукт успешно добавлен в калькулятор"); | ||
| } | ||
| } | ||
| } | ||
| } |
| 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; | ||
| } | ||
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Можно перенести инициализацию в место объявления