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
Open
marugish
wants to merge
3
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
3 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 |
|---|---|---|
| @@ -1 +1,8 @@ | ||
| # Пустой репозиторий для работы с Java кодом в Android Studio | ||
|
|
||
| Вся логика взаимодействия с пользователем описана в классе Main: | ||
| - Программа запрашивает у пользователя, на скольких человек разделить счёт и проверяет данные на корректность с помощью if/else, а также try/catch. | ||
| - При успешном вводе количества человек (>1) на вход принимает информацию о товарах. Эта информация попадает в класс Calculator. | ||
| - Класс Calculator состоит из основных методов: подсчёт общей стоимости для каждого пользователя, добавление в список товаров, а также вывод списка на экран после добавления всех. | ||
| - Каждый товар - объект класса Product c двумя полями: "название товара" и "цена", а также конструктором. | ||
| - Класс Formatter состоит из двух основных методов, которые помогают с выводом на экран: округление суммы до двух знаков после запятой и склонение валюты "рубль". |
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,28 @@ | ||
| public class Calculator { | ||
| int users; | ||
| double totalCost = 0.00; | ||
| String listOfProducts = ""; | ||
|
|
||
| Calculator(int users) { | ||
| this.users = users; | ||
| } | ||
|
|
||
| void addProduct(Product product) { | ||
| totalCost += product.costOfProduct; | ||
| // формируем список продуктов заранее | ||
| Formatter formatter = new Formatter(); | ||
| listOfProducts = listOfProducts + "\n" + product.nameOfProduct + " - " | ||
| + formatter.roundingTheDouble(product.costOfProduct) | ||
| + formatter.displayCurrency(product.costOfProduct); | ||
| System.out.println("Товар успешно добавлен."); | ||
| } | ||
|
|
||
| void displayProducts() { | ||
| System.out.println("Добавленнные товары:" + listOfProducts); | ||
| } | ||
|
|
||
| double calculateScoreForEachPerson() { | ||
| return totalCost / users; | ||
| } | ||
|
|
||
| } | ||
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,25 @@ | ||
| public class Formatter { | ||
| String roundingTheDouble(double totalCostForEach) { | ||
| return String.format("%.2f", totalCostForEach); | ||
| } | ||
|
|
||
| String displayCurrency(double totalCostForEach) { | ||
| String currency; | ||
| String standardCurrency = " рублей."; | ||
| int cost = (int) Math.floor(totalCostForEach); | ||
| int preCalcCost = cost % 100; | ||
| switch (cost % 10) { | ||
| case 1 -> { | ||
| if (preCalcCost == 11) currency = standardCurrency; | ||
| else currency = " рубль."; | ||
| } | ||
| case 2, 3, 4 -> { | ||
| if (preCalcCost >= 12 && preCalcCost <= 14) | ||
| currency = standardCurrency; | ||
| else currency = " рубля."; | ||
| } | ||
| default -> currency = standardCurrency; | ||
| } | ||
| return currency; | ||
| } | ||
| } |
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,63 @@ | ||
| import java.util.InputMismatchException; | ||
| import java.util.Scanner; | ||
|
|
||
| public class Main { | ||
|
|
||
| public static void main(String[] args) { | ||
| System.out.println("Hello world!"); | ||
| Scanner scanner = new Scanner(System.in); | ||
| Formatter formatter = new Formatter(); | ||
| while (true) { | ||
| System.out.println("На скольких человек разделить счёт?"); | ||
| try { | ||
| int persons = scanner.nextInt(); | ||
| scanner.nextLine(); | ||
| if (persons < 1) System.out.println("Ошибка: некорректное число пользователей."); | ||
| else if (persons == 1) System.out.println("Ошибка: делить ничего не требуется."); | ||
| else { | ||
| System.out.println("Успех: корректное число пользователей, можете воспользоваться калькулятором."); | ||
| Calculator calculator = new Calculator(persons); | ||
| while (true) { | ||
| System.out.println("Введите название товара:"); | ||
| String nameOfProduct = scanner.nextLine().trim(); | ||
| if (nameOfProduct.isEmpty()) { | ||
| System.out.println("Ошибка: некорректная длина названия товара."); | ||
| } else { | ||
| double costOfProduct; | ||
| while (true) { | ||
| System.out.println("Введите стоимость товара (Формат: рубли,копейки):"); | ||
| try { | ||
| costOfProduct = scanner.nextDouble(); | ||
| scanner.nextLine(); | ||
| if (costOfProduct <= 0.00) { | ||
| System.out.println("Ошибка: некорректная цена, введите положительное число."); | ||
| } else break; | ||
| } catch (InputMismatchException e) { | ||
| System.out.println("Ошибка: недопустимый тип ввода."); | ||
| scanner.nextLine(); | ||
| } | ||
| } | ||
| // Можно создавать и добавлять в список новый продукт | ||
| Product product = new Product(nameOfProduct, costOfProduct); | ||
| calculator.addProduct(product); | ||
|
|
||
| System.out.println("Добавить ещё товар?"); | ||
| String usersAnswer = scanner.nextLine(); | ||
| if (usersAnswer.equalsIgnoreCase("завершить")) break; | ||
| } | ||
| } | ||
| // Вывод результатов пользователю | ||
| calculator.displayProducts(); | ||
| double scoreForEachPerson = calculator.calculateScoreForEachPerson(); | ||
| System.out.println("Итоговая стоимость: " | ||
| + formatter.roundingTheDouble(scoreForEachPerson) | ||
| + formatter.displayCurrency(scoreForEachPerson)); | ||
| break; | ||
| } | ||
| } catch (InputMismatchException e) { | ||
| System.out.println("Ошибка: недопустимый тип ввода. Требуется ввести целое число."); | ||
| scanner.nextLine(); | ||
| } | ||
| } | ||
| scanner.close(); | ||
| } | ||
| } |
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 nameOfProduct; | ||
| double costOfProduct; | ||
|
|
||
| Product(String nameOfProduct, double costOfProduct) { | ||
| this.nameOfProduct = nameOfProduct; | ||
| this.costOfProduct = costOfProduct; | ||
| } | ||
| } |
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.
Рекомендация: Форматирование кода - в Java принят немного другой стиль форматирования кода. Если не вдаваться в детали, то легко и быстро отформатировать код в Android Studio можно следующей комбинацией клавиш: в Windows Ctrl + Alt + L , в MacOs ⌘ + ⌥ + L.