forked from Yandex-Practicum/Java-Module-Project
-
Notifications
You must be signed in to change notification settings - Fork 0
Pull Request к заданию Пишем консольное приложение #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
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
3 changes: 3 additions & 0 deletions
.idea/.gitignore
Oops, something went wrong.
6 changes: 6 additions & 0 deletions
.idea/compiler.xml
Oops, something went wrong.
19 changes: 19 additions & 0 deletions
.idea/gradle.xml
Oops, something went wrong.
9 changes: 9 additions & 0 deletions
.idea/misc.xml
Oops, something went wrong.
6 changes: 6 additions & 0 deletions
.idea/vcs.xml
Oops, something went wrong.
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
22 changes: 0 additions & 22 deletions
src/main/java/Calculator.java
Oops, something went wrong.
17 changes: 0 additions & 17 deletions
src/main/java/Formatter.java
Oops, something went wrong.
10 changes: 0 additions & 10 deletions
src/main/java/Item.java
Oops, something went wrong.
129 changes: 97 additions & 32 deletions
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,49 +1,114 @@ | ||
| import java.util.Locale; | ||
| import java.util.Scanner; | ||
|
|
||
| public class Main { | ||
|
|
||
| public static void main(String[] args) { | ||
| Scanner scanner = new Scanner(System.in); | ||
|
|
||
| int friendCount; | ||
| while (true) { | ||
| System.out.println("На сколько человек необходимо разделить счет?"); | ||
| friendCount = scanner.nextInt(); | ||
|
|
||
| if (friendCount > 1) { | ||
| break; | ||
| } else if (friendCount == 1) { | ||
| System.out.println( | ||
| "Нет смысла делить сумму на одного человека. Давайте попробуем ввести другое значение, которое будет больше единицы."); | ||
| } else { | ||
| System.out.println("Неверное количество друзей. Значение должно быть болье единицы, давайте попробуем еще раз."); | ||
| } | ||
| } | ||
| // Начало программы | ||
| int amountMan = inputAmountMan(); // Получение количества человек для расчета из метода | ||
| System.out.println("Количество человек для расчета - " + amountMan + "."); | ||
| float sumProductPrice = requestProduct(); // Получение общей суммы всех товаров из метода | ||
| float everyonePays = sumProductPrice / amountMan; // Получение расчета на каждого человека | ||
| String rublesEveryonePays = nameRubles(everyonePays); // Получение падежа слова "рубль" из метода | ||
| String messageTemplate = "Каждому счет обойдется в %.2f %s."; | ||
| String finalOutputText = String.format(messageTemplate, everyonePays, rublesEveryonePays); | ||
| finalOutputText = finalOutputText.replace(',', '.'); // Вывод точки вместо запятой (как указано в задании) | ||
| System.out.println(finalOutputText); | ||
| } | ||
|
|
||
| Calculator calculator = new Calculator(friendCount); | ||
| private static int inputAmountMan() { // Метод ввода количества человек для разделения счета | ||
| // Объявление метода, возвращеющего значение типа int | ||
| System.out.println("Введите количество человек, на которое будет разделен счет"); | ||
| Scanner scanner = new Scanner(System.in); // Создание объекта "сканер" | ||
|
|
||
| while (true) { | ||
| System.out.println("Введите название товара"); | ||
| String name = scanner.next(); | ||
| int inputMan; // Объявление переменной "количество человек" | ||
| while (true) { // Запускаем бесконечный цикл | ||
|
|
||
| System.out.println("Введите стоимость товара в формате: 'рубли.копейки' [10.45, 11.40]"); | ||
| double price = scanner.nextDouble(); | ||
| if (scanner.hasNextInt()) { // Условие, если введено значение типа int | ||
| inputMan = scanner.nextInt(); // Ввод с клавиатуры количества человек для разделения счета | ||
|
|
||
| calculator.addItem(new Item(name, price)); | ||
| if (inputMan > 1) { // Если введено корректное значение больше 1 | ||
| break; // Выходим из бесконечного цикла | ||
| } else if (inputMan == 1) { // Если пользователь вводит 1 | ||
| System.out.println("Программа производит расчеты при количестве человек от 2-х и больше, попробуйте еще раз."); | ||
| } | ||
| else { | ||
| System.out.println("Некорректное значение, попробуйте еще раз."); | ||
| } | ||
| } else { // Если пользователь ввел с клавиатуры символ или значение типа отличного от int | ||
| System.out.println("Не балуйтесь с вводом значений. Вводите целое неотрицательное число, большое или равное 2"); | ||
| System.out.println("\nВведите количество человек, на которое будет разделен счет"); | ||
| scanner.nextLine(); // переход на следующую строку считывания для того, чтобы избежать бесконечного вывода | ||
| } | ||
| } | ||
| return inputMan; | ||
| } | ||
| public static float calcPrice () { // Метод ввода стоимости товара | ||
| Scanner scanner = new Scanner(System.in).useLocale(Locale.US); // Создание объекта "сканер" | ||
| float priceProduct; // Переменная стоимости продукта | ||
| System.out.println("Введите стоимость продукта в формате 'рубли.копейки' [10.45, 11.40]:"); | ||
| while (true) { // Запускаем бесконечный цикл | ||
| if (scanner.hasNextFloat()) { // Условие, если введено значение типа float | ||
| priceProduct = scanner.nextFloat(); // Ввод с клавиатуры стоимости товара | ||
| if (priceProduct > 0.00) { // Если введено корректное значение больше 0.00 | ||
| break; // Выходим из бесконечного цикла | ||
| } else if (priceProduct <= 0.00) { // Если пользователь вводит 0.00 | ||
| System.out.println("Некорректное значение, стоимость должна быть больше 0.00"); | ||
| } | ||
| } else { // Если пользователь ввел с клавиатуры некоректные значения | ||
| System.out.println("Не балуйтесь с вводом значений. Вводите дробное неотрицательное число, большое или равное 1 копейке (0.01)."); | ||
| scanner.nextLine(); // переход на следующую строку считывания для того, чтобы избежать бесконечного вывода | ||
| } | ||
| } | ||
| return priceProduct; | ||
| } | ||
|
|
||
| System.out.println( | ||
| "Хотите добавить еще один товар? Введите любой символ для продолжения, либо 'Завершить' если больше нет товаров для добавления"); | ||
| String answer = scanner.next(); | ||
| public static float requestProduct() { // Метод подсчета общей стоимости товаров | ||
|
|
||
| if (answer.equalsIgnoreCase("Завершить")) { | ||
| break; | ||
| Scanner scanner = new Scanner(System.in);// Создание объекта "сканер" | ||
| String addedProduct = ""; // Объявление переменной "Добавленные товары" и присваивание "" | ||
| float priceProductOne; // Объявление переменной стоимости одного продукта | ||
| float sumPrice = 0.00F; // Объявление переменной "Общая сумма всех товаров" и присваивание "0.00" | ||
| String continueProgram; // Объявление переменной продолжения или завершения расчетов | ||
| while (true) { // Бесконечный цикл | ||
| System.out.println("Введите название товара"); | ||
| String nameProduct = scanner.nextLine(); // Ввод имени товара | ||
| priceProductOne = calcPrice(); // Вызов функции и получение стоимости товара | ||
| Product newProduct = new Product(nameProduct, priceProductOne); // Создание экземпляра класса product c атрибутами "Имя товара", "Стоимость" | ||
| System.out.println("Товар " + newProduct.productName + " успешно добавлен."); | ||
| addedProduct = addedProduct + "\n" + newProduct.productName + ";"; // Перечень всех добавленных продуктов | ||
| sumPrice = sumPrice + newProduct.productPrice; // Общая стоимость всех продуктов | ||
| System.out.println("Добавленные товары:" + addedProduct); | ||
| System.out.println("Общая сумма: " + sumPrice); | ||
| System.out.println("Хотите ли добавить еще один товар? (введите 'завершить' для расчета стоимости или любой другой символ для продолжения)"); | ||
| continueProgram = scanner.nextLine(); // Считываем желание пользователя завершить или не завершать программу | ||
| if (continueProgram.equalsIgnoreCase("Завершить")) { // Условие выхода из бесконечного цикла | ||
| break; // Выходим из бесконечного цикла | ||
| } | ||
| System.out.println("Продолжаем добавлять товары"); | ||
| } | ||
| return sumPrice; // Возвращение общей стоимости всех товаров | ||
| } | ||
|
|
||
| double result = calculator.divideSum(); | ||
| Formatter formatter = new Formatter(); | ||
| public static String nameRubles (float sum) { // Метод определения падежа для слова "рубль" | ||
|
|
||
| System.out.println(calculator.cart); | ||
| System.out.println("Каждому человеку к оплате: " + formatter.roundResult(result) + " " + formatter.formatValue(result)); | ||
| float finalNumberSum = (float) Math.floor(sum); // Округление в меньшую сторону | ||
| String nameRublesOut; // Объявление строки конечного падежа | ||
| // Вывод полученного падежа слова "рубль" | ||
| if (finalNumberSum >= 10.0 && finalNumberSum <= 20.0) { // Если на каждого человека от от 10 до 20 рублей | ||
| nameRublesOut = "рублей"; | ||
| } | ||
| else { // Иначе в зависимости от последней цифры в числе | ||
| finalNumberSum = finalNumberSum % 10; | ||
| if (finalNumberSum == 1.0) { | ||
| nameRublesOut = "рубль"; | ||
| } | ||
| else if (finalNumberSum >= 2.0 && finalNumberSum <= 4.0) | ||
| nameRublesOut = "рубля"; | ||
| else { | ||
| nameRublesOut = "рублей"; | ||
| } | ||
| } | ||
| return nameRublesOut; // То возвращяем "рублей" | ||
| } | ||
| } |
9 changes: 9 additions & 0 deletions
src/main/java/Product.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,9 @@ | ||
| public class Product { | ||
| String productName; // Наименование товара | ||
| float productPrice; // Цена товара | ||
|
|
||
| Product(String productName, float productPrice) { | ||
| this.productName = productName; | ||
| this.productPrice = productPrice; | ||
| } | ||
| } |
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.