Repository navigation
Консольное приложение 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
NieCloud
wants to merge
9
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
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
8ce5207
Added Guests class, allowing to calculate number of guests based on u…
NieCloud 1ffd4d9
Created calculator to analyze user input and give an answer on how th…
NieCloud be134c7
For better understanding of the class purpose, changed it from Calcul…
NieCloud 5b09eb1
For better understanding of the class purpose, changed it from Calcul…
NieCloud c2374cc
Merge remote-tracking branch 'origin/dev' into dev
NieCloud a8fd9ff
Added check for non-negative cost of goods
NieCloud c0fceaa
Now goods private value doesnt update until it is in line with restri…
NieCloud 03cdc44
Now RoubleFormatter works correctly with values above 100.
NieCloud 3a39bcf
Now RoubleFormatter works correctly with values above 100.
NieCloud 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,88 @@ | ||
| import java.util.Scanner; | ||
|
|
||
| public class Goods { | ||
| private double totalBill = 0; | ||
| private String goods = ""; | ||
|
|
||
| /** | ||
| Метод создает String со списком товаров и их ценой, а также суммирует все товары | ||
| в отдельную переменную totalBill | ||
| */ | ||
| public void createListOfGoods() { | ||
| String tempGoods = ""; | ||
| String userInputGoodName; | ||
| double userInputGoodValue; | ||
| Scanner scanner = new Scanner(System.in); | ||
|
|
||
| while (true) { | ||
| if (tempGoods.isEmpty()) { | ||
| System.out.println("Введите название товара (Или \"Завершить\" для окончания формирования списка):"); | ||
| } else { | ||
| System.out.println("Введите название следующего товара (Или \"Завершить\" для окончания формирования списка):"); | ||
| } | ||
|
|
||
| userInputGoodName = scanner.nextLine(); | ||
|
|
||
| if (userInputGoodName.equalsIgnoreCase("Завершить")) { | ||
| break; | ||
| } | ||
|
|
||
| if (tempGoods.isEmpty()) { | ||
| tempGoods = tempGoods.concat(userInputGoodName); | ||
| } else { | ||
| tempGoods = tempGoods.concat("\n" + userInputGoodName); | ||
| } | ||
|
|
||
| System.out.println("Введите стоимость товара в формате рубли.копейки (например 10.22):"); | ||
|
|
||
| while (true) { | ||
| userInputGoodValue = checkUserInputAsDouble(); | ||
| if (userInputGoodValue < 0) { | ||
| System.out.println("Стоимость товара должна быть неотрицательной"); | ||
| } else { | ||
| break; | ||
| } | ||
| } | ||
|
|
||
| totalBill += userInputGoodValue; | ||
| tempGoods = tempGoods.concat(String.format(" - Цена: %.2f", userInputGoodValue)); | ||
| } | ||
| goods = tempGoods; | ||
| } | ||
|
|
||
| /** | ||
| Метод проверяет, является ли ввод пользователя double | ||
| */ | ||
| private double checkUserInputAsDouble() { | ||
| Scanner scanner = new Scanner(System.in); | ||
| double correctDoubleInput; | ||
|
|
||
| while (true) { | ||
| try { | ||
| correctDoubleInput = Double.parseDouble(scanner.next()); | ||
| break; | ||
| } catch (NumberFormatException e) { | ||
| System.out.println("Введите корректную стоимость в формате рубли.копейки (например 10.22):"); | ||
| } | ||
|
Comment on lines
+61
to
+66
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. Отличный способ проверки на корректность ввода 👍 |
||
| } | ||
|
|
||
|
|
||
| return correctDoubleInput; | ||
| } | ||
|
|
||
| /** | ||
| Метод выводит, сколько каждый человек должен заплатить в зависимости от | ||
| введенного количества гостей | ||
| */ | ||
| public void calculateAndShowResultsPerGuest(int numberOfGuests) { | ||
| if (goods.isEmpty()) { | ||
| System.out.println("Никаких товаров не было добавлено"); | ||
| return; | ||
| } | ||
| System.out.println("Добавленные товары: \n" + goods); | ||
| double billPerPerson = totalBill / numberOfGuests; | ||
| String roubles = RoubleFormatter.returnRoubleString(billPerPerson); | ||
| System.out.println(String.format("Каждый человек должен заплатить %.2f %s", billPerPerson, roubles)); | ||
| } | ||
|
|
||
| } | ||
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,46 @@ | ||
| import java.util.Scanner; | ||
|
|
||
| public class Guests { | ||
| private int numberOfGuests = 0; | ||
|
|
||
| /** | ||
| Метод устанавливает количество гостей, на которых необходимо разделить счет, на основе | ||
| ввода пользователя через консоль | ||
| */ | ||
| public void setNumberOfGuests() { | ||
| System.out.println("На скольких человек необходимо разделить счет?"); | ||
| while (true) { | ||
| int tempNumberOfGuests = returnCorrectUserInputAsInt(); | ||
| if (tempNumberOfGuests > 1) { | ||
| numberOfGuests = tempNumberOfGuests; | ||
| break; | ||
| } if (tempNumberOfGuests == 1) { | ||
| System.out.println("На одного счет делить смысла нет"); | ||
| } if (tempNumberOfGuests < 1) { | ||
| System.out.println("Число должно быть больше 1"); | ||
| } | ||
|
|
||
| } | ||
| } | ||
|
|
||
| /** | ||
| Метод проверяет, является ли ввод пользователя int | ||
| */ | ||
| private int returnCorrectUserInputAsInt() { | ||
| Scanner scanner = new Scanner(System.in); | ||
| int correctIntInput; | ||
| while (true) { | ||
| try { | ||
| correctIntInput = Integer.parseInt(scanner.next()); | ||
| break; | ||
| } catch (NumberFormatException e) { | ||
| System.out.println("Введите корректное целое число гостей"); | ||
| } | ||
| } | ||
| return correctIntInput; | ||
| } | ||
|
|
||
| public int getNumberOfGuests() { | ||
| return numberOfGuests; | ||
| } | ||
| } |
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,14 @@ | ||
|
|
||
| public class Main { | ||
| public static void main(String[] args) { | ||
| System.out.println("Hello world!"); | ||
| Guests firstGuestList = new Guests(); | ||
| firstGuestList.setNumberOfGuests(); | ||
|
|
||
| Goods testGoods = new Goods(); | ||
|
|
||
|
|
||
| testGoods.createListOfGoods(); | ||
| testGoods.calculateAndShowResultsPerGuest(firstGuestList.getNumberOfGuests()); | ||
|
|
||
| } | ||
| } |
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,15 @@ | ||
| public class RoubleFormatter { | ||
| public static String returnRoubleString(double sum) { | ||
| int integerValueOfSum = (int) sum; | ||
| if (integerValueOfSum % 100 > 10 && integerValueOfSum % 100 < 20) { | ||
| return "рублей"; | ||
| } | ||
| if (integerValueOfSum % 10 == 1) { | ||
| return "рубль"; | ||
| } else if (integerValueOfSum % 10 >= 2 && integerValueOfSum % 10 <= 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.
🍏 Думаю, что можно было создать один сканер в main и передавать его как аргумент в методы, в которых он необходим
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.
Некоторые методы я отметил private, которые используют Scanner, потому что они исполняют техническую работу внутри класса и не должны быть доступны вне класса. Поэтому из main не хотелось бы им передавать сканер...