-
Notifications
You must be signed in to change notification settings - Fork 0
Первое задание #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
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,22 +1,25 @@ | ||
| class Calculator { | ||
|
|
||
| int friendsCount; | ||
| public class Calculator { | ||
| private int peopleNumber; | ||
| private double sum; | ||
| private String productList = ""; | ||
|
|
||
| String cart = "Добавленные товары:"; | ||
| double totalPrice = 0; | ||
|
|
||
| Calculator(int friendsCount) { | ||
| this.friendsCount = friendsCount; | ||
| public Calculator(int peopleNumber){ | ||
| this.peopleNumber = peopleNumber; | ||
| } | ||
|
|
||
| void addItem(Item item) { | ||
| totalPrice += item.price; | ||
| cart = cart + "\n" + item.name; | ||
| public void addProduct(Product product){ | ||
| this.sum = this.sum + product.getPrice(); | ||
| this.productList = this.productList.concat(product.getName() + "\n"); | ||
| System.out.println("Товар " + product.getName() + " на сумму = " + product.getPrice() + " успешно добавлен"); | ||
| } | ||
|
|
||
| System.out.println(item.name + " в корзине"); | ||
| public void printProductList(){ | ||
| System.out.println(this.productList); | ||
| } | ||
|
|
||
| double divideSum() { | ||
| return totalPrice / friendsCount; | ||
| public double calculateSumToPay(){ | ||
| return sum / peopleNumber; | ||
| } | ||
|
|
||
| } | ||
This file was deleted.
This file was deleted.
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -4,46 +4,81 @@ public class Main { | |
|
|
||
| public static void main(String[] args) { | ||
| Scanner scanner = new Scanner(System.in); | ||
| int personNumber = getPersonNumber(); | ||
| double sumToPay; | ||
|
|
||
| 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("Неверное количество друзей. Значение должно быть болье единицы, давайте попробуем еще раз."); | ||
| } | ||
| } | ||
|
|
||
| Calculator calculator = new Calculator(friendCount); | ||
|
|
||
| while (true) { | ||
| // Создается калькулятор | ||
| Calculator calculator = new Calculator(personNumber); | ||
| // Пользователь вводит наименование и стоимость товара для подсчета | ||
| boolean stopEnterProduct = false; | ||
| boolean stopEnterPrice = false; | ||
| while (!stopEnterProduct){ | ||
|
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. Можно ещё сделать бесконечный цикл while(true), а в if(productName.equalsIgnoreCase("завершить")) выходить из цикла при помощи break. Тогда отпадет необходимость дальнейшие действия заворачивать в else + не будем создавать дополнительную переменную stopEnterProduct. |
||
| System.out.println("Введите название товара"); | ||
| String name = scanner.next(); | ||
| if (scanner.hasNextLine()){ | ||
| String productName = scanner.nextLine(); | ||
| if(productName.equalsIgnoreCase("завершить")){ | ||
| stopEnterProduct = true; | ||
| } else { | ||
| // Пользователь вводит стоимость товара для подсчета | ||
| while (!stopEnterPrice){ | ||
|
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("Введите стоимость товара в рублях"); | ||
| if(scanner.hasNextDouble()){ | ||
| double productPrice = scanner.nextDouble(); | ||
| if (productPrice < 0){ | ||
| System.out.println("Некорректное значение"); | ||
| continue; | ||
| } | ||
| Product product = new Product(productName, productPrice); | ||
| calculator.addProduct(product); | ||
|
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. Можно добавлять в список сразу при добавлении в список: |
||
| scanner.nextLine(); | ||
| stopEnterPrice = true; | ||
| } else { | ||
| if (scanner.nextLine().equalsIgnoreCase("завершить")) { | ||
| stopEnterPrice = true; | ||
| } else{ | ||
| System.out.println("Некорректное значение"); | ||
| } | ||
|
|
||
| System.out.println("Введите стоимость товара в формате: 'рубли.копейки' [10.45, 11.40]"); | ||
| double price = scanner.nextDouble(); | ||
| } | ||
| } | ||
| } | ||
| } | ||
| } | ||
| System.out.println("Добавленные товары:"); | ||
|
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. Имеет смысл выносить такие большие логические фрагменты в отдельные методы по примеру метода getPersonNumber(). Это делает программу больше удобочитаемой, когда разнородная логика не смешивается в один сплошной код. |
||
| calculator.printProductList(); | ||
|
|
||
| calculator.addItem(new Item(name, price)); | ||
| sumToPay = calculator.calculateSumToPay(); | ||
|
|
||
| System.out.println( | ||
| "Хотите добавить еще один товар? Введите любой символ для продолжения, либо 'Завершить' если больше нет товаров для добавления"); | ||
| String answer = scanner.next(); | ||
| if (Math.floor(sumToPay) == 1) | ||
| System.out.println(String.format("Каждый должен заплатить по %.2f рубль",sumToPay)); | ||
| else if (Math.floor(sumToPay) == 2 || Math.floor(sumToPay) == 3 || Math.floor(sumToPay) == 4) | ||
| System.out.println(String.format("Каждый должен заплатить по %.2f рубля",sumToPay)); | ||
| else | ||
| System.out.println(String.format("Каждый должен заплатить по %.2f рублей",sumToPay)); | ||
|
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. Строка ""Каждый должен заплатить по %.2f" встречается несколько раз в программе, имеет смысл вынести её в отдельную переменную и затем к ней прибавлять рубли в нужном виде. Основное преимущество такого подхода - при необходимости поменять текст надо будет поменять только текст в переменной без риска что-нибудь забыть |
||
| } | ||
|
|
||
| if (answer.equalsIgnoreCase("Завершить")) { | ||
| break; | ||
| public static int getPersonNumber(){ | ||
| // Запрашиваем у пользователя количество человек, на которых нужно разделить счет | ||
| Scanner scanner = new Scanner(System.in); | ||
| int personNumber; | ||
| while (true){ | ||
| System.out.println("На скольких человек нужно разделить счет?"); | ||
| if(scanner.hasNextInt()){ | ||
| personNumber = scanner.nextInt(); | ||
| if (personNumber == 1){ | ||
| System.out.println("Нет смысла что то считать и делить"); | ||
| } | ||
| else if (personNumber < 1){ | ||
| System.out.println("Некорректное значение для подсчета"); | ||
| } | ||
| else { | ||
| return personNumber; | ||
| } | ||
| } else{ | ||
| System.out.println("Некорректное значение для подсчета"); | ||
| scanner.nextLine(); | ||
| } | ||
| } | ||
|
|
||
| double result = calculator.divideSum(); | ||
| Formatter formatter = new Formatter(); | ||
|
|
||
| System.out.println(calculator.cart); | ||
| System.out.println("Каждому человеку к оплате: " + formatter.roundResult(result) + " " + formatter.formatValue(result)); | ||
| } | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,16 @@ | ||
| public class Product { | ||
| // Описывает продук? который можно добавить для подсчета в калькулятор | ||
| private String name; | ||
| private double price; | ||
|
|
||
| public Product(String name, double price){ | ||
| this.name = name; | ||
| this.price = price; | ||
| } | ||
| public String getName(){ | ||
| return name; | ||
| } | ||
| public double getPrice(){ | ||
| return price; | ||
| } | ||
| } |
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.
Можно ещё обойтись без
this.(хотя и такие варианты встречаются), а также использовать конструкциюsum += product.getPrice();