Repository navigation
Завершенное задание #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
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,21 @@ | ||
| public class Formater { | ||
| public static void format(double sum){ | ||
|
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. Как и с классом |
||
| String rub; | ||
| if(sum % 100 >= 10 && sum % 100 <= 19){ | ||
| rub = "рублей"; | ||
| } else if (sum % 10 >= 2 && sum % 10 < 5){ | ||
| rub = "рубля"; | ||
| } else if (sum % 10 >= 1 && sum % 10 < 2){ | ||
| rub = "рубль"; | ||
| } else { | ||
| rub = "рублей"; | ||
| } | ||
| Formater formater = new Formater(); | ||
| formater.result(sum, rub); | ||
|
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. Для вызове функции result нет необходимости создавать еще один объект класса В комментарии c67a4c4#r1114363706 я имел в виду возможность избавить класс Formater от логики вывода данных. Все, что возвращал бы его метод А в месте вызова данного метода уже бы обрабатывалась логика вывода данных |
||
|
|
||
| } | ||
| public static void result(double sum, String rub){ | ||
| String result = String.format("%.2f",sum); | ||
| System.out.println("Сумма с каждого = " + result + " " + rub); | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,59 @@ | ||
| import java.util.Scanner; | ||
|
|
||
| public class GroceryList { | ||
| public void product(int people) { | ||
| double sum = 0.0; | ||
| String products = ("Добавленные товары:"); | ||
|
|
||
| while (true) { | ||
| Scanner priceProduct = new Scanner(System.in); | ||
|
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. Название Поэтому предлагаю для данной переменной использовать название просто |
||
| System.out.println("Введите название товара"); | ||
| String name = priceProduct.nextLine(); | ||
|
|
||
|
|
||
| System.out.println("Введите стоимость товара"); | ||
|
|
||
|
|
||
| while(true) { | ||
| if (!priceProduct.hasNextDouble()) { | ||
| System.out.println("Ошибка, введён текст\nВведите числовое значение"); | ||
| priceProduct.nextLine(); | ||
| } else { | ||
| double price = priceProduct.nextDouble(); | ||
|
|
||
| if (price < 0) { | ||
| System.out.println("Ошибка, отрицательное значение\nВведите положительное значение"); | ||
| } | ||
|
|
||
| if (price >= 0) { | ||
| products = products + "\n" + name + " по цене " + price; | ||
| sum = sum + price; | ||
|
|
||
| System.out.println("Товар успешно добавлен"); | ||
| break; | ||
| } | ||
| } | ||
| } | ||
|
|
||
|
|
||
| System.out.println("Хотите добавить ещё один товар?"); | ||
|
|
||
| priceProduct.nextLine(); | ||
| String reply = priceProduct.nextLine(); | ||
|
|
||
| if (reply.equalsIgnoreCase("Завершить")) { | ||
| System.out.println(products); | ||
| break; | ||
| } | ||
|
|
||
| } | ||
|
|
||
| System.out.println("Общая сумма товаров = " + sum); | ||
| sum = sum / people; | ||
| Formater formater = new Formater(); | ||
| formater.format(sum); | ||
|
|
||
| } | ||
| } | ||
|
|
||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,8 +1,38 @@ | ||
| // dev branch for Y.Practicum | ||
| import java.util.Scanner; | ||
|
|
||
| public class Main { | ||
|
|
||
| public static void main(String[] args) { | ||
| // ваш код начнется здесь | ||
| // вы не должны ограничиваться только классом Main и можете создавать свои классы по необходимости | ||
| System.out.println("Привет Мир"); | ||
|
|
||
| Scanner scanner = new Scanner(System.in); | ||
| System.out.println("На скольких человек поделить счёт?"); | ||
|
|
||
|
|
||
| while (true) { | ||
| if (!scanner.hasNextInt()) { | ||
| System.out.println("Ошибка, введён текст\nВведите числовое значение"); | ||
| scanner.nextLine(); | ||
| } else { | ||
| int people = scanner.nextInt(); | ||
|
|
||
| if (people == 1) { | ||
| System.out.println("Зачем тебе делить свою еду?\nВведите другое количество"); | ||
| } | ||
| if (people < 1) { | ||
| System.out.println("А положительных друзей у тебя нет?\nВведите положительное число"); | ||
| } | ||
| if (people > 1) { | ||
| System.out.println("Давай считать"); | ||
| GroceryList groceryList = new GroceryList(); | ||
| groceryList.product(people); | ||
| break; | ||
| } | ||
|
|
||
|
|
||
| } | ||
|
|
||
| } | ||
|
|
||
| } | ||
| } |
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.
Хорошая идея вынести в отдельный класс логику форматирования суммы!
Я бы посоветовал вынести из функции
formatлогику вывода результата в консоль и просто отдаватьresultв качестве результата работы метода.При таком подходе мы повышаем гибкость нашей программы. Например, если в следующий спринтах при разработке уже Android-приложения нам потребуется функционал форматирования, то мы сможем легко переиспользовать наш класс без внесения изменений формата вывода данных.
Это один из ярких примеров принципа единственной ответственности из принципов SOLID