Repository navigation
Консольное приложение. Проектная работа №1. Проверка 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
Open
AlexOtkidach
wants to merge
2
commits into
main
Choose a base branch
from
dev
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
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
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,48 @@ | ||
| public class Calculator { | ||
| private final int sumGuests; | ||
| private double totalPrice; | ||
| public String list = ""; | ||
|
|
||
| public Calculator(int sumGuests) { | ||
|
|
||
| this.sumGuests = sumGuests; | ||
|
|
||
| } | ||
|
|
||
| public void add(Product p) { | ||
| totalPrice += p.price; | ||
|
|
||
| list += p.productName + "\n"; | ||
| } | ||
|
|
||
| public String getResult() { | ||
| var part = totalPrice / sumGuests; | ||
| //Чтобы округлить дробное число только до двух чисел после запятой, можно использовать строковый шаблон: String.format("%.2f", double);. | ||
| var r = String.format("%.2f", part); | ||
|
|
||
| //Чтобы поставить правильное окончание, вы можете округлить дробное значение и вывести слово "рубль" в правильном падеже. Для округления дробного числа в меньшую сторону можно использовать метод floor() класса Math. | ||
| var rub = Math.floor(part); | ||
|
|
||
| var suffix = getSuffix(rub); | ||
|
|
||
| return r + " рубл" + suffix; | ||
| } | ||
|
|
||
| public static String getSuffix(double rub) { | ||
| // 0,5 - 20 ей | ||
| // 1:ь | ||
| // 2,3,4я | ||
| if (rub % 100 >= 11 && rub%100 <= 14){ | ||
| return "ей"; | ||
| } | ||
| else if (rub % 10 == 1) { | ||
| return "ь"; | ||
| } else if (rub % 10 == 2 || rub % 10 == 3 || rub % 10 == 4) { | ||
| return "я"; | ||
| } else { | ||
| return "ей"; | ||
| } | ||
|
|
||
| } | ||
|
|
||
| } |
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,101 @@ | ||
| import java.sql.SQLOutput; | ||
| import java.util.InputMismatchException; | ||
| import java.util.Scanner; | ||
|
|
||
| public class Main { | ||
| public static void main(String[] args) { | ||
| System.out.println("Hello world!"); | ||
|
|
||
| //1. После запуска программа должна спрашивать у пользователя, на скольких человек необходимо разделить счёт. | ||
| System.out.println("Привет! На сколько человек мне разделить счет?"); | ||
| //2. Программа должна выводить сообщение об ошибке, когда: | ||
| //- Количество человек, введённых пользователем, равно 1. В этом случае нет смысла ничего считать и делить. | ||
| Scanner scanner = new Scanner(System.in); | ||
| int sumGuests = 0; | ||
|
|
||
| while (true) { | ||
| try { | ||
| sumGuests = scanner.nextInt(); | ||
| } catch (InputMismatchException ex) { | ||
| System.out.println("Введите число!"); | ||
| } finally { | ||
| scanner.nextLine(); | ||
| } | ||
| //- Количество человек меньше 1. Это некорректное значение для подсчёта. | ||
| if (sumGuests > 1) { | ||
| System.out.println("Вас " + sumGuests + " человека? Класс, тогда давайте поделим счет!"); | ||
| break; | ||
| } | ||
| if (sumGuests == 1) { | ||
| System.out.println("Вы один? Жаль, но к сожалению тут делить нечего, кроме слез одиночества;) "); | ||
| } | ||
| //Если значение некорректное, то показать ошибку и заново попросить пользователя ввести корректное количество гостей. | ||
| if (sumGuests <= 0) { | ||
| System.out.println("Ой, кажется вы ошиблись;)! Введите от 2х человек и мы попробуем снова!"); | ||
| } | ||
| System.out.println("Давайте попробуем снова: "); | ||
|
|
||
| } | ||
| //System.out.println("Давайте попробуем снова: "); | ||
| var c = new Calculator(sumGuests); | ||
| while (true) { | ||
| //Запросите у пользователя название товара и его стоимость. Стоимость должна быть в формате рубли.копейки, например 10.45 или 11.40. | ||
| String productName; | ||
| System.out.println("Какой у вас товар?"); | ||
| productName = scanner.nextLine(); | ||
| System.out.println("Напишите стоимость продукта: "); | ||
| double price = inputPrice(scanner); | ||
|
|
||
| //Полученный товар должен быть добавлен в калькулятор. | ||
| var p = new Product(productName, price); | ||
| c.add(p); | ||
| //При добавлении товара в калькулятор нужно считать текущую общую сумму всех товаров. | ||
| //Калькулятор должен запоминать названия всех добавленных товаров, чтобы выводить все товары, которые были в него добавлены. | ||
| //После добавления товара в калькулятор нужно показать пользователю сообщение об успешном добавлении товара. | ||
| System.out.println("Товар успешно добавлен!\nМожет еще по одной;)"); | ||
| //После добавления товара нужно спрашивать у пользователя, хочет ли он добавить ещё один товар. | ||
| //Пользователь должен ввести команду "Завершить" для того, чтоб завершить процесс добавления товаров. | ||
| //Введение любого другого символа или слова должно запрашивать у пользователя следующий товар до тех пор, пока пользователь не введёт команду "Завершить" после добавления товара. | ||
| //Пользователь может ввести команду "Завершить" в любом регистре (завершить, ЗАВЕРШИТЬ, заВЕрШиТь и пр.), и это должно завершать процесс добавления товара. | ||
|
|
||
| var input = scanner.nextLine(); | ||
|
|
||
| if (input.equalsIgnoreCase("завершить")) { | ||
| break; | ||
|
|
||
| } | ||
| } | ||
| //После того как пользователь введёт команду "Завершить" после добавления товаров, нужно показать пользователю все добавленные товары и посчитать, сколько должен заплатить каждый человек. | ||
| //Каждый новый добавленный товар должен быть выведен с новой строки после текста: "Добавленные товары:". Вы можете использовать символ \n в строке, чтобы указать компилятору, | ||
| // что нужно сделать в этом месте переноса строки. | ||
| System.out.println("Добавленные товары: "); | ||
| System.out.println(c.list); | ||
| //Вывод суммы, которую должен заплатить каждый человек, должен быть в формате "10.45". Дробная часть не должна содержать больше двух чисел после запятой. | ||
| //Сумма считается в рублях. Ваша задача — обработать правильный вывод. Если сумма 1.45, то вы должны вывести "1.45 рубль", а если сумма будет 3.20 или 4.00, вы | ||
| // должны вывести 3.20 рубля или 4.00 рубля. Окончания в слове "рубль" должны зависеть от целочисленной части. | ||
| System.out.println(c.getResult()); | ||
| } | ||
|
|
||
|
|
||
| private static double inputPrice(Scanner scanner) { | ||
| while (true) { | ||
| try { | ||
| var r = scanner.nextDouble(); | ||
| if (r <= 0) { | ||
| System.out.println("Цена должна быть положительной!"); | ||
| continue; | ||
| } | ||
| return r; | ||
| } catch (InputMismatchException ext) { | ||
| System.out.println("Введите число!"); | ||
| } finally { | ||
| scanner.nextLine(); | ||
| } | ||
|
|
||
| } | ||
|
|
||
| } | ||
| } | ||
| } | ||
|
|
||
|
|
||
|
|
||
|
|
||
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,13 @@ | ||
| import java.util.Scanner; | ||
|
|
||
| public class Product { | ||
| public final String productName; | ||
| public final double price; | ||
|
|
||
|
|
||
| public Product(String productName, double price) { | ||
|
|
||
| this.productName = productName; | ||
| this.price = price; | ||
| } | ||
| } |
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.
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.
Такие отдельные логические блоки, как этот (ввод и обработка количества людей), а также логические блоки с вводом товаров и выводом результатов лучше выносить в отдельные методы и затем вызывать их там, где необходимо. Это позволяет улучшить читаемость кода, т.к. разнородная логика не смешивается в один сплошной код, а также упрощает поддержку кода.
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.
Понял, поправлю и буду обращать внимание.