forked from Yandex-Practicum/Java-Module-Project-YP
-
Notifications
You must be signed in to change notification settings - Fork 0
Console application for dividing the bill total among a number of payers. #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
Open
Changes from all commits
Commits
Show all changes
2 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
12 changes: 11 additions & 1 deletion
README.md
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 +1,11 @@ | ||
| # Пустой репозиторий для работы с Java кодом в Android Studio | ||
| # Приложение для разделения общего счета на равные платежи. | ||
| Данное приложение позволяет разделить сумму общего счета (например в ресторане) на равные платежи для распределения между участниками мероприятия. | ||
| Для использования приложения: | ||
| 1. Введите количество участников, на которых надо будет разделить счет | ||
| 2. Введите товары и суммы из чека | ||
| - Сначала вводится наименование товара/услуги | ||
| - Затем вводится стоимость товара/услуги (разделителем целой и дробной части является точка '.', цифры после второго знака после запятой игнорируются) | ||
| - Затем требуется ввести команду 'Завершить', если все затраты введены, либо любую строку или символ для продолжения ввода товаров/услуг | ||
| 3. После завершения ввода будет выведен перечень всех затрат по чеку, итоговая сумма и размер платежа каждого участника | ||
|
|
||
| Прошу обратить внимание! В случае, если общая сумма не делится на количество участников без остатка, то платеж платеж каждого округляется в большую сторону. При этом сумма переплаты также указывается в итоговом расчете. |
10 changes: 10 additions & 0 deletions
src/main/java/CheckItem.java
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,10 @@ | ||
| public class CheckItem { | ||
| final String itemName; | ||
| final double value; | ||
|
|
||
| public CheckItem(String item, double value) { | ||
| this.itemName = item; | ||
| this.value = value; | ||
| } | ||
|
|
||
| } |
52 changes: 51 additions & 1 deletion
src/main/java/Main.java
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,56 @@ | ||
| import java.util.Locale; | ||
|
|
||
| public class Main { | ||
| public static void main(String[] args) { | ||
| System.out.println("Hello world!"); | ||
|
|
||
| Locale.setDefault(Locale.US); // Для использования точки в качестве разделителя целой и дробной части double | ||
| SharedCalc calculator = new SharedCalc(); | ||
|
|
||
| // Стадия 1: Выводим инструкции работы с программой | ||
| System.out.println("Приложение для разделения общего счета на равные платежи."); | ||
| System.out.println(" 1. Введите количество участников"); | ||
| System.out.println(" 2. Введите товары и суммы (в отдельной строке наименование товара, в следующей сумма)"); | ||
| System.out.println(" 3. Введите 'Завершить' по окончании ввода товаров"); | ||
| System.out.println("Вы получите список товаров и сумму для оплаты каждым участником.\n"); | ||
|
|
||
| // Стадия 2: Цикл получения количества участников | ||
| System.out.println("Введите количество участников (не меньше 2х):"); | ||
| while (true) { | ||
| int persons = ScanValues.scanIntegerValue(); | ||
| if (persons > 1) { | ||
| System.out.printf("Счет будет разделен на %d %s%n", persons, WordEndings.convertPersons(persons)); | ||
| // Сообщаем калькулятору количество персон для разделения счета | ||
| calculator.setPersons(persons); | ||
| break; | ||
| } else System.out.printf("Введенное число %d неверно! Требуется число больше 2х.", persons); | ||
| } | ||
|
|
||
| // Стадия 3: Добавляем товары и суммы | ||
| System.out.println("Вводите по-строчно товары и стоимость:"); | ||
| while (true) { | ||
| System.out.println("Введите название товара:"); | ||
| String item = ScanValues.scanStringValue(); | ||
| System.out.println("Теперь введите стоимость, например 12.34:"); | ||
| double value = ScanValues.scanDoublePositiveValue(); | ||
| // Добавляем полученные значения в калькулятор и вывод сообщения об их добавлении | ||
| CheckItem newItem = new CheckItem(item, value); | ||
| calculator.addItem(newItem); | ||
| System.out.printf("Добавлен товар '%s' стоимостью %.2f %s, в чеке %d %s на сумму %.2f %s%n", | ||
| item, | ||
| value, | ||
| WordEndings.convertRubles((int) Math.floor(value)), | ||
| calculator.items.size(), | ||
| WordEndings.convertGoods(calculator.items.size()), | ||
| calculator.getTotal(), | ||
| WordEndings.convertRubles((int) Math.floor(calculator.getTotal()))); | ||
|
|
||
| // Стадия 4: Выводим результат | ||
| System.out.println("Введите 'Завершить' для окончания или любое слово для продолжения"); | ||
| if (ScanValues.scanStringValue().equalsIgnoreCase("Завершить")) { | ||
| // Выводим статистику и завершаем цикл | ||
| System.out.println(calculator.getResultAsString()); | ||
| break; | ||
| } | ||
| } | ||
| } | ||
| } |
42 changes: 42 additions & 0 deletions
src/main/java/ScanValues.java
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,42 @@ | ||
| import java.util.Scanner; | ||
|
|
||
| public class ScanValues { | ||
| private static final Scanner scanner = new Scanner(System.in); | ||
| public static int scanIntegerValue() { | ||
| while (true) { | ||
| if (scanner.hasNextInt()) return scanner.nextInt(); | ||
| else { | ||
| System.out.println("Некорректный ввод! Введите целое число, например 15:"); | ||
| scanner.nextLine(); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| public static double scanDoublePositiveValue() { | ||
| while (true) { | ||
| if (scanner.hasNextDouble()) { | ||
| double scannedValue = scanner.nextDouble(); | ||
| if (scannedValue > 0) return Math.floor(scannedValue * 100) / 100; | ||
| else { | ||
| System.out.println("Стоимость не может быть отрицательной или нулевой, введите снова."); | ||
| scanner.nextLine(); | ||
| } | ||
| } | ||
| else { | ||
| System.out.println("Некорректный ввод! Введите число с разделителем, например 12.34:"); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| public static String scanStringValue() { | ||
| while (true) { | ||
| String result = scanner.next(); | ||
| if (!result.isEmpty()) return result; | ||
| else { | ||
| System.out.println("Пустое значение! Введите заново."); | ||
| scanner.nextLine(); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| } |
50 changes: 50 additions & 0 deletions
src/main/java/SharedCalc.java
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,50 @@ | ||
| import java.util.ArrayList; | ||
|
|
||
| public class SharedCalc { | ||
| private int persons; | ||
| private double total; | ||
| ArrayList<CheckItem> items = new ArrayList<>(); | ||
|
|
||
| public void setPersons(int persons) { | ||
| this.persons = persons; | ||
| } | ||
|
|
||
| public SharedCalc() { | ||
| this.persons = 0; | ||
| this.total = 0f; | ||
| } | ||
| public void addItem(CheckItem item) { | ||
| items.add(item); | ||
| total += item.value; | ||
| } | ||
|
|
||
| public double getTotal() { | ||
| return total; | ||
| } | ||
|
|
||
| public String getResultAsString() { | ||
| StringBuilder completeList = new StringBuilder(); | ||
| // Формируем чек в виде строки | ||
| System.out.println("Добавленные товары:"); | ||
| for (int i = 0; i < items.size(); i++) { | ||
| completeList.append(String.format("%s\n\t\t\t%.2f %s\n", | ||
| items.get(i).itemName, | ||
| items.get(i).value, | ||
| WordEndings.convertRubles((int) Math.floor(items.get(i).value)))); | ||
| } | ||
| completeList.append("------------------------\n"); | ||
| completeList.append(String.format("Итого:\n\t\t\t%.2f %s\n", | ||
| total, | ||
| WordEndings.convertRubles((int) Math.floor(total)))); | ||
| completeList.append("------------------------\n"); | ||
| double eachPart = Math.ceil(total / persons * 100) / 100; | ||
| completeList.append(String.format("С каждого по %.2f %s", | ||
| eachPart, | ||
| WordEndings.convertRubles((int) Math.floor(eachPart)))); | ||
| // Проверяем остаток и если он есть, то делаем приписку | ||
| double rest = total - eachPart * persons; | ||
| if (rest < 0) completeList.append(String.format(",\nа лишние %.2f %s в качестве чаевых.", -rest, WordEndings.convertRubles((int) Math.floor(-rest)))); | ||
| return completeList.toString(); | ||
| } | ||
|
|
||
| } |
18 changes: 18 additions & 0 deletions
src/main/java/WordEndings.java
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,18 @@ | ||
| public class WordEndings { | ||
| public static String convertWord(String root, String oneItemEnd, String twoItemsEnd, String manyItemsEnd, int count) { | ||
| if (count % 10 == 1 && !(count / 10 % 10 == 1)) return root + oneItemEnd; // Если существительное в единственном числе | ||
| else if (count % 10 > 1 && count % 10 < 5 && !(count / 10 % 10 == 1)) return root + twoItemsEnd; // Если существительное от 2 до 4, кроме дцать | ||
| else return root + manyItemsEnd; // Если существительное во множественном числе | ||
| } | ||
|
|
||
| public static String convertRubles(int count) { | ||
| return convertWord("рубл", "ь", "я", "ей", count); | ||
| } | ||
|
|
||
| public static String convertPersons(int count) { | ||
| return convertWord("персон", "у", "ы", "", count); | ||
| } | ||
| public static String convertGoods(int count) { | ||
| return convertWord("товар", "", "а", "ов", count); | ||
| } | ||
| } |
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.