forked from Yandex-Practicum/Java-Module-Project-YP
-
Notifications
You must be signed in to change notification settings - Fork 0
Project work 1 #1
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
Open
ArtemSh13
wants to merge
6
commits into
dev
Choose a base branch
from
project-work-1
base: dev
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
91e90aa
Add logic of enter of number of persons
ArtemSh13 395d70b
Add logic of enter of goods and prices
ArtemSh13 6948833
Add logic of output of goods and prices
ArtemSh13 9f5bd7e
Move enter of number of persons to separate class
ArtemSh13 de195e7
Move enter of goods and prices to Calculator class
ArtemSh13 64e83d9
Move all logic to separate methods of Calculator class
ArtemSh13 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,123 @@ | ||
| import java.util.HashMap; | ||
| import java.util.Map; | ||
| import java.util.Scanner; | ||
|
|
||
| public class Calculator { | ||
| private int numberOfPersons; | ||
| private HashMap<String, Double> goodsAndPrices; | ||
|
|
||
| // Метод проверяет, что строка - целое положительное число | ||
| private boolean isThisNumber(String input) { | ||
| return input.matches("^[1-9][0-9]*$"); | ||
|
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. Ты сначала проверяешь строку на соответствие регулярке, а потом парсишь |
||
| } | ||
|
|
||
| public void enterNumberOfPersons() { | ||
| Scanner scanner = new Scanner(System.in); | ||
| int numberOfPersons = -1; | ||
|
|
||
| while (numberOfPersons <= 1) { | ||
| System.out.println("На скольких человек необходимо разделить счёт?"); | ||
| String userInput = scanner.nextLine(); | ||
|
|
||
| if (!this.isThisNumber(userInput)) { | ||
| System.out.println("Некорректное значение. Нужно ввести целое число больше 1"); | ||
| } else if (Integer.parseInt(userInput) == 1) { | ||
| System.out.println("Нет смысла ничего считать и делить - вы ели в одиночку!"); | ||
| } else { | ||
| numberOfPersons = Integer.parseInt(userInput); | ||
| } | ||
| } | ||
| this.numberOfPersons = numberOfPersons; | ||
| } | ||
|
|
||
| // Метод проверяет, что строка - шаблонная пара "товар - цена" | ||
| // Цена считается корректной в том числе для | ||
| // - цен меньше 1 рубля | ||
| // - цены в 0 рублей 0 копеек (например, подарок от заведения) | ||
| private boolean isThisGoodAndPrice(String input) { | ||
| return input.matches("^.+ - (([1-9][0-9]*)|0)\\.[0-9]{2}$"); | ||
| } | ||
|
|
||
| public void enterGoodsAndPrices() { | ||
|
|
||
| String stopTotalPriceCommand = "завершить"; | ||
| this.goodsAndPrices = new HashMap<>(); | ||
| String userCommand = "пока не завершили"; | ||
|
|
||
|
|
||
| while (!userCommand.equals(stopTotalPriceCommand)) { | ||
| System.out.println("Введите название товара и его стоимость в формате:\n<название товара> - <рубли>.<копейки>\nДля копеек всегда используйте ДВЕ цифры"); | ||
|
|
||
| Scanner scanner = new Scanner(System.in); | ||
| String userInput = scanner.nextLine(); | ||
|
|
||
| if (this.isThisGoodAndPrice(userInput)) { | ||
| String[] goodAndPrice = userInput.split(" - "); | ||
| double nextPrice = Double.parseDouble(goodAndPrice[1]); | ||
| this.goodsAndPrices.put(goodAndPrice[0], nextPrice); | ||
| System.out.println("Товар успешно добавлен"); | ||
|
|
||
| System.out.println("Введите \"завершить\", чтобы закончить ввод. Чтобы добавить ещё товар, введите любые другие символы"); | ||
| userCommand = scanner.nextLine().toLowerCase(); | ||
| } else { | ||
| System.out.println("Ввод некорректен. Пожалуйста, следуйте инструкции"); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| // По числу определяет, в каком падеже должно быть слово "рубли" | ||
| private String getRublePostfix(double sum) { | ||
| String rublePostfix; | ||
|
|
||
| if (sum >= 5 && sum < 21) { | ||
| rublePostfix = "рублей"; | ||
| } else { | ||
| int sumRemainder = (int) sum / 10; | ||
| rublePostfix = switch (sumRemainder) { | ||
| case 1 -> "рубль"; | ||
| case 2, 3, 4 -> "рубля"; | ||
| default -> "рублей"; | ||
| }; | ||
| } | ||
| return rublePostfix; | ||
| } | ||
|
|
||
| // Проверяет, что в объекте есть и количество персон, и список товаров с ценами | ||
| private boolean isAllFieldsFilled() { | ||
| if (this.numberOfPersons == 0) { | ||
| System.out.println("Список товаров пуст!"); | ||
| } | ||
| if (this.goodsAndPrices == null) { | ||
| System.out.println("Список товаров пуст!"); | ||
| } | ||
| return this.numberOfPersons != 0 && this.goodsAndPrices != null; | ||
| } | ||
|
|
||
| public void printGoodsAndPrices() { | ||
| if (this.isAllFieldsFilled()) { | ||
| System.out.println("Добавленные товары:"); | ||
| for (Map.Entry<String, Double> entry : this.goodsAndPrices.entrySet()) { | ||
| System.out.println(entry.getKey() + " - " + entry.getValue() + " " + this.getRublePostfix(entry.getValue())); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| private double getSumPerPerson() { | ||
| double total = 0.0; | ||
| if (this.isAllFieldsFilled()) { | ||
| for (Map.Entry<String, Double> entry : this.goodsAndPrices.entrySet()) { | ||
| total += entry.getValue(); | ||
| } | ||
| return total / this.numberOfPersons; | ||
| } | ||
| return total; | ||
| } | ||
|
|
||
| public void printSumPerPerson() { | ||
| if (this.isAllFieldsFilled()) { | ||
| double sumPerPerson = this.getSumPerPerson(); | ||
| System.out.println("Каждый человек должен заплатить " + String.format("%.2f", sumPerPerson) + " " + this.getRublePostfix(sumPerPerson)); | ||
| } | ||
| } | ||
|
|
||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,6 +1,17 @@ | ||
|
|
||
| public class Main { | ||
| public static void main(String[] args) { | ||
| System.out.println("Hello world!"); | ||
|
|
||
| Calculator calculator = new Calculator(); | ||
|
|
||
| // 1. Входные параметры для счётчика | ||
| calculator.enterNumberOfPersons(); | ||
|
|
||
| // 2. Добавление товаров в калькулятор | ||
| calculator.enterGoodsAndPrices(); | ||
|
|
||
| // 3. Вывод результатов | ||
| calculator.printGoodsAndPrices(); | ||
| calculator.printSumPerPerson(); | ||
| } | ||
| } | ||
| } | ||
|
|
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
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.
Выбор коллекции не кажется обоснованным. Каждый новый продукт по сути это новое значение в мапе, а мапа занимает больше памяти, чем обычный список. Поэтому кажется, что простой
ArrayListподойдёт лучше для хранения какого-нибудь классаProductс двумя полями - названием и ценой