forked from Yandex-Practicum/Java-Module-Project-YP
-
Notifications
You must be signed in to change notification settings - Fork 0
111 #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
KailarStern
wants to merge
4
commits into
main
Choose a base branch
from
dev
base: main
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
111 #1
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
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 |
|---|---|---|
| @@ -1,8 +1,101 @@ | ||
| public class Main { | ||
| import java.util.Scanner; | ||
|
|
||
| public class Main { | ||
| public static void main(String[] args) { | ||
| // ваш код начнется здесь | ||
| // вы не должны ограничиваться только классом Main и можете создавать свои классы по необходимости | ||
| System.out.println("Привет Мир"); | ||
| Scanner scanner = new Scanner(System.in); | ||
|
|
||
| int guests = Calculator.getGuestsNumber(scanner); | ||
| String itemList = Calculator.getItemsList(scanner); | ||
| double costPerPerson = Calculator.getCostPerPerson(itemList, guests); | ||
|
|
||
| String rubleSuffix = Calculator.getRubleSuffix(costPerPerson); | ||
| System.out.println("Каждый гость должен заплатить " + String.format("%.2f", costPerPerson) + " " + rubleSuffix + "."); | ||
| } | ||
| } | ||
|
|
||
| class Calculator { | ||
|
|
||
| public static int getGuestsNumber(Scanner scanner) { | ||
| int guests = 0; | ||
| boolean guestsNum = false; | ||
| while (!guestsNum) { | ||
| System.out.print("Введите количество гостей: "); | ||
| if (scanner.hasNextInt()) { | ||
| guests = scanner.nextInt(); | ||
| if (guests <= 1) { | ||
| System.out.println("Некорректное значение. Количество гостей должно быть больше 1."); | ||
| } else { | ||
| guestsNum = true; | ||
| } | ||
| } else { | ||
| System.out.println("Введите корректное число!"); | ||
| scanner.next(); | ||
| } | ||
| } | ||
| return guests; | ||
| } | ||
|
|
||
| public static String getItemsList(Scanner scanner) { | ||
| double totalValue = 0.0; | ||
| boolean isGoodsEnough = true; | ||
| String itemList = ""; | ||
| while (isGoodsEnough) { | ||
| System.out.print("Введите название товара: "); | ||
| String itemName = scanner.next(); | ||
|
|
||
| boolean validCost = false; | ||
| while (!validCost) { | ||
| System.out.print("Введите стоимость товара (в формате рубли.копейки): "); | ||
| if (scanner.hasNextDouble()) { | ||
| double itemCost = scanner.nextDouble(); | ||
| if (itemCost >= 0) { | ||
| totalValue += itemCost; | ||
| itemList += itemName + " - " + String.format("%.2f", itemCost) + " руб." + "\n"; | ||
| System.out.println("Товар " + itemName + " успешно добавлен."); | ||
| validCost = true; | ||
| } else { | ||
| System.out.println("Стоимость товара не может быть отрицательной."); | ||
| } | ||
| } else { | ||
| System.out.println("Введите корректное число!"); | ||
| scanner.next(); | ||
| } | ||
| } | ||
|
|
||
| System.out.print("Хотите добавить ещё один товар? (Введите \"Завершить\", чтобы закончить): "); | ||
| String userChoice = scanner.next(); | ||
| if (userChoice.equalsIgnoreCase("Завершить")) { | ||
| isGoodsEnough = false; | ||
| } | ||
| } | ||
|
|
||
| System.out.println("Добавленные товары: "); | ||
| System.out.println(itemList); | ||
| return itemList; | ||
| } | ||
|
|
||
| public static double getCostPerPerson(String itemList, int guests) { | ||
| double totalValue = 0; | ||
| String[] items = itemList.split("\n"); | ||
| for (String item : items) { | ||
| String costString = item.substring(item.lastIndexOf(" ") + 1, item.lastIndexOf(" руб.")); | ||
| totalValue += Double.parseDouble(costString); | ||
| } | ||
| return totalValue / guests; | ||
| } | ||
|
|
||
| public static String getRubleSuffix(double costPerPerson) { | ||
| int rubles = (int) costPerPerson; | ||
| int lastDigit = rubles % 10; | ||
| int lastTwoDigits = rubles % 100; | ||
| if (lastTwoDigits >= 11 && lastTwoDigits <= 19) { | ||
| return "рублей"; | ||
| } else if (lastDigit == 1) { | ||
| return "рубль"; | ||
| } else if (lastDigit >= 2 && lastDigit <= 4) { | ||
| return "рубля"; | ||
| } else { | ||
| return "рублей"; | ||
| } | ||
| } | ||
| } | ||
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.
Весьма интересное решение.
В любом случае, приложение может падать из-за неверно определенного индекса item.lastIndexOf(" ") + 1. Начиная с конца, этот метод вернет индекс пробела, который стоит перед "руб.", вдобавок к этому индексу прибавляем +1. Далее определяем индекс item.lastIndexOf(" руб."), с которого начинается " руб."
Получается такая картина

Ошибка возникает из-за того, что мы пытаемся из строки выдернуть отрезок с 13 по 12 индекс. Можно внести исправления таким образом и будет работать:
Но все также получится не очень хороший способ. По сути костыль)
По хорошему, ты мог в классе Calculator создать статичные переменные. Например вот такие
Куда сложил бы все необходимое для вычислений и парсить строки, чтобы вычленить оттуда число не пришлось бы. Но все же плюс, за такую идею)
На доработку не буду отправлять, т.к. остальное работает как часы. Просто внеси исправления, которые я тебе предложил