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
base: main
Are you sure you want to change the base?
Changes from all commits
c8cc4b1
c6a2918
e4b39ab
196a8b3
c9e861b
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,33 @@ | ||
| import java.util.Scanner; | ||
|
|
||
| class CountingPeople { // Метод спрашивает кол-во людей для выставления счета; | ||
| int result = 0; | ||
| public int calculate() { | ||
| Scanner scanner = new Scanner(System.in); | ||
| do { | ||
| System.out.println("На сколько человек считать счет?"); | ||
| while (true) // Проверка на то, чтобы ввели именно число. Можно было бы вынести в отдельный метод. Но в контексте работы, не хотелось бы. | ||
| { | ||
| if (scanner.hasNextDouble() || scanner.hasNextLong() || scanner.hasNextInt()) | ||
| { | ||
| result = Integer.parseInt(scanner.nextLine()); | ||
| break; | ||
| } | ||
| else | ||
| { | ||
| System.out.println("Вы ввели не число, так на сколько человек счет считать?"); | ||
| scanner.nextLine(); | ||
| }} | ||
| if (result == 1) { | ||
| System.out.println("А что тут считать, 1 и есть 1"); | ||
| } else if (result > 1) { | ||
| System.out.println("Понял, счет делим на " + result); | ||
| return result; | ||
| } else { | ||
| System.out.println("Это некорректное значение для подсчёта, введи снова"); | ||
| } | ||
| } | ||
| while (result <= 1); | ||
| return result; | ||
| } | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,24 @@ | ||
| public class Good { | ||
| public double price = 0.00; | ||
| public String name = "New Good"; | ||
|
|
||
| public String goodCreated(String name, double price) { // Метод создания товара. | ||
| this.priceSet(price); | ||
| this.nameSet(name); | ||
| String formattedDouble = String.format("%.2f", this.price); // Можно было бы вынести в отдельный метод, чтобы было DRY, но не вижу смысла; | ||
| String goodCreated = this.name + formattedDouble; | ||
| return goodCreated; | ||
| } | ||
|
|
||
| public double priceSet(double price) { | ||
| this.price = price; | ||
| // System.out.println("Price has set " + this.price); | ||
| return this.price; | ||
| } | ||
|
|
||
| public String nameSet(String name) { | ||
|
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. То же самое |
||
| this.name = name; | ||
| // System.out.println("Name has set " + this.name); | ||
| return this.name; | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,6 +1,16 @@ | ||
|
|
||
| public class Main { | ||
| int result; | ||
|
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. Переменная объявляется, но нигде не используется |
||
| public static void main(String[] args) { | ||
| System.out.println("Hello world!"); | ||
| CountingPeople count = new CountingPeople(); // Отдельный класс подсчета кол-ва людей; | ||
| int result = count.calculate(); // Считаем кол-во людей; | ||
| newGoodGenerator generator = new newGoodGenerator(); // Калькулятор из задания наывается в моем решении генератором; | ||
| do{ | ||
| generator.generateNewGood(); // Создаем первый товар; | ||
| } while (generator.askingMoreGoods()); // Тут спрашиваем нужны ли еще товары; | ||
| // System.out.println("Добавили все товары, какие мы хотели"); | ||
| generator.showTotalPrice(); | ||
| generator.bill(result); // Метод проводит расчет по покупкам; | ||
| } | ||
| } | ||
| } | ||
|
|
||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,90 @@ | ||
| import java.util.Scanner; | ||
|
|
||
| public class newGoodGenerator { // Добавить с большой буквы; Классы в JAVA с большой буквы. | ||
|
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. Да, классы в Java пишутся в PascalCase:) |
||
| String nameToSet = "Nameless Good"; | ||
| double priceToSet = 00.00; | ||
| double totalPrice = 00.00; | ||
| public String allGoods = "Список всех товаров: " + "\n"; | ||
|
|
||
| public String generateNewGood() { | ||
|
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 scanner = new Scanner(System.in); | ||
| System.out.println("Введите название товара, чтобы добавить его"); | ||
| // String descriptionArrived = scanner.next(); Была ошибка, что считывал только до пробела и выкидывал ошибку. | ||
| this.nameToSet = scanner.nextLine(); | ||
| do { | ||
| System.out.println("Введите цену товара, чтобы добавить ее (рубли.копейки)"); | ||
| while (true) // Проверка на то, чтобы ввели положительное число. Можно было бы вынести в отдельный метод. Но в контексте работы, не хотелось бы. | ||
| { | ||
| if (scanner.hasNextDouble() || scanner.hasNextLong() || scanner.hasNextInt()) { | ||
| this.priceToSet = Double.parseDouble(scanner.nextLine()); | ||
| if (this.priceToSet < 1) { | ||
| System.out.println("Вы ввели отрицательное число: " + this.priceToSet); | ||
| } | ||
| break; | ||
| } else { | ||
| System.out.println("Вы ввели не число, повторите"); | ||
| scanner.nextLine(); | ||
| } | ||
| } | ||
| } while (this.priceToSet <= 1); | ||
| Good goodToSend = new Good(); // Создаем новый товар из класса Good; | ||
| String goodAdded = goodToSend.goodCreated(this.nameToSet, this.priceToSet); | ||
| this.addingNewGood(this.nameToSet, this.priceToSet); | ||
| return goodAdded; | ||
| } | ||
|
|
||
| public boolean askingMoreGoods() { // | ||
| Scanner scanner = new Scanner(System.in); | ||
| System.out.println("Нужны еще товары, нажмите 'Enter'. Чтобы завершить программу введите 'Завершить'"); | ||
| String userReply = scanner.nextLine(); | ||
| if (userReply.equalsIgnoreCase("Завершить")) // Выход из цикла по условиям задачи; | ||
| { | ||
| return false; | ||
| } else { | ||
| System.out.println("Добавляем еще один товар"); | ||
| return true; | ||
| } | ||
| } | ||
|
|
||
| public void addingNewGood(String name, double price) { | ||
| String formattedDouble = String.format("%.2f", price); // Можно было бы вынести в отдельный метод, чтобы было DRY, но не вижу смысла; | ||
| System.out.println("Товар был добавлен в корзину: " + formattedDouble + " " + name); | ||
| String goodDescription = formattedDouble + " - " + name + "; "; | ||
| totalPrice += price; | ||
| System.out.println("Цена всего заказа: " + formattedDouble); | ||
| allGoods = allGoods.concat(goodDescription + "\n"); | ||
| System.out.println(allGoods); | ||
| } | ||
|
|
||
| public String showTotalPrice() { // Метод показывает общую форму заказа; | ||
|
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 в пустоту |
||
| String formattedDouble = String.format("%.2f", totalPrice); // Можно было бы вынести в отдельный метод, чтобы было DRY, но не вижу смысла; | ||
| System.out.println("Цена всего заказа: " + formattedDouble); | ||
| return formattedDouble; | ||
| } | ||
|
|
||
| public void bill(int peopleCount) { // Метод, который выставляет счет. Он делит общую сумму на кол-во людей; | ||
| double result = totalPrice / peopleCount; | ||
| System.out.println(allGoods); | ||
| System.out.printf("Каждый человек заплатит %.2f %s", result, declinationOfRub(result)); | ||
| } | ||
| public String declinationOfRub(double result){ | ||
| int num = (int) result; | ||
| int preLastDigit = num % 100 / 10; | ||
| if (preLastDigit == 1) | ||
| { | ||
| return "рублей"; | ||
| } | ||
| switch (num % 10) | ||
| { | ||
| case 1: | ||
| return "рубль"; | ||
| case 2: | ||
| case 3: | ||
| case 4: | ||
| return "рубля"; | ||
| default: | ||
| return "рублей"; | ||
| } | ||
| } | ||
|
|
||
| } | ||
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.price = price;, после чегоreturn this.price;в пустоту. Лучше сделать void и ничего не возвращать