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
PhilipMaslov1
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 |
|---|---|---|
| @@ -0,0 +1,34 @@ | ||
| public class Bill { | ||
| int numberOfPerson = 1; //Количество участников (по умолчанию 1) | ||
| String listOfProducts = ""; // Список продуктов в корзине | ||
| double sum = 0; // Стоимость всех продуктов в корзине | ||
|
|
||
| void setNumberOfPerson () { | ||
| this.numberOfPerson = ConsoleReader.askNumberOfPerson(); | ||
| } | ||
| void addProduct (Product product) { | ||
| listOfProducts += String.format("%.2f руб. - %s\n", product.price, product.name); | ||
| sum += product.price; | ||
| System.out.printf("Товар \"%s\" стоимостью %.2f руб. добавлен в корзину.\n", product.name, product.price); | ||
| } | ||
| void printBill() { | ||
| System.out.printf("\nДобавленные товары:\n------\n%s------\n%.2f руб. - сумма всех товаров.\n\n", this.listOfProducts, this.sum); | ||
| } | ||
|
|
||
| // Метод выводит сообщение с долей каждого участника. | ||
| // Если сумма не может быть разделена поровну, | ||
| // считаем сколько должен заплатить каждый участник (в максимально равных долях). | ||
| void printParticipantAmount () { | ||
| double sumPerPerson = Calculator.getSumPerPerson(this); | ||
| double remOfDivision = Calculator.getRemOfDivision(this); | ||
| double lastParticipantPart = sumPerPerson + remOfDivision; | ||
|
|
||
| if (Calculator.getRemOfDivision(this) == 0) | ||
| System.out.printf("Счёт можно разделить поровну.\nКаждый должен заплатить по %.2f %s", sumPerPerson, Formatter.endOfRoubles(sumPerPerson)); | ||
| else { | ||
| System.out.print("Счёт ровно не делится:"); | ||
| System.out.printf("\n- доля %d из %d людей составит %.2f %s", numberOfPerson - 1, numberOfPerson, sumPerPerson, Formatter.endOfRoubles(sumPerPerson)); | ||
| System.out.printf("\n- доля одного составит %.2f %s\n", lastParticipantPart, Formatter.endOfRoubles(lastParticipantPart)); | ||
| } | ||
| } | ||
| } |
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,12 @@ | ||
| public class Calculator { | ||
| static double getSumPerPerson(Bill bill){ | ||
| return Math.round(bill.sum / bill.numberOfPerson * 100) / 100.0; | ||
| } | ||
| static double getRemOfDivision(Bill bill) { | ||
| double sumPerPerson = Calculator.getSumPerPerson(bill); | ||
| return Math.round((bill.sum - sumPerPerson * bill.numberOfPerson) * 100) / 100.0; | ||
| } | ||
| static double roundDouble (Double d) { | ||
| return Math.round(d * 100) / 100d; | ||
| } | ||
| } | ||
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,62 @@ | ||
| import java.util.Locale; | ||
| import java.util.Scanner; | ||
|
|
||
| // TODO ToDo: нужно добавить обработку переполнений при считывании числовых значений и выполнении математических операций. | ||
|
|
||
| public class ConsoleReader { | ||
|
|
||
| public static Scanner scanner = new Scanner(System.in); | ||
| static int askNumberOfPerson () { | ||
| int numberOfPerson; | ||
| do { | ||
| System.out.println("Укажите количество людей (шт.): "); | ||
| while (!scanner.hasNextInt()) { | ||
| scanner.next(); | ||
| System.err.print("Нужно ввести число.\n"); | ||
| System.out.println("Укажите количество людей (шт.): "); | ||
| } | ||
| numberOfPerson = scanner.nextInt(); | ||
| if (numberOfPerson <= 1) { | ||
| System.err.println("Количество должно быть больше 1"); | ||
| } else { | ||
| return numberOfPerson; | ||
| } | ||
| } while (true); | ||
| } | ||
| static String askProductName () { | ||
| String name; | ||
| System.out.println("Введите название товара:"); | ||
| name = scanner.next(); | ||
| return name; | ||
| } | ||
| static double askProductPrice () { | ||
| scanner.useLocale(Locale.US); | ||
| double price; | ||
| do { | ||
| System.out.println("Введите стоимость в формате \"руб.коп\":"); | ||
| while (!scanner.hasNextDouble()){ | ||
| scanner.next(); | ||
| System.err.println("Не верный формат значения."); | ||
| System.out.println("Введите стоимость в формате \"руб.коп\":"); | ||
| } | ||
| price = scanner.nextDouble(); | ||
| if (Calculator.roundDouble(price) <= 0) { | ||
| System.err.println("Стоимость должна быть больше нуля."); | ||
| } else { | ||
| return Calculator.roundDouble(price); | ||
| } | ||
|
|
||
| } while (true); | ||
| } | ||
| static boolean askToAddProduct(){ | ||
| System.out.println("\nДобавить ещё один товар?\n\"Да (или любой символ)\" - добавить товар,\n\"Завершить\" - закончить ввод и посчитать сумму."); | ||
| if (scanner.next().equalsIgnoreCase("Завершить")) { | ||
| return true; | ||
| } else { | ||
| return false; | ||
| } | ||
| } | ||
| static void scannerClose (){ | ||
| 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,16 @@ | ||
| public class Formatter { | ||
|
|
||
| // Метод возвращает слово "рубль" с окончанием, в зависимости от суммы. | ||
| static String endOfRoubles (double sum) { | ||
| int intSum = (int) Math.floor(sum); | ||
| if (intSum >= 10 && intSum <= 14) | ||
| return "рублей."; | ||
| else | ||
| return switch (intSum - 10 * (intSum / 10)) { | ||
| case 1 -> "рубль."; | ||
| case 2, 3, 4 -> "рубля."; | ||
| case 5, 6, 7, 8, 9, 0 -> "рублей."; | ||
| default -> "руб."; | ||
| }; | ||
| } | ||
| } |
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,20 @@ | ||
|
|
||
| public class Main { | ||
| public static void main(String[] args) { | ||
| System.out.println("Hello world!"); | ||
|
|
||
| Bill bill = new Bill(); | ||
| bill.setNumberOfPerson(); | ||
|
|
||
| while (true) { | ||
| Product product = new Product(); | ||
| product.setName(); | ||
| product.setPrice(); | ||
| bill.addProduct(product); | ||
| if (ConsoleReader.askToAddProduct()) { | ||
| bill.printBill(); | ||
| bill.printParticipantAmount(); | ||
| ConsoleReader.scannerClose(); | ||
| break; | ||
| } | ||
| } | ||
| } | ||
| } |
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,11 @@ | ||
| public class Product { | ||
| String name; // Название продукта | ||
| double price; // Цена продукта | ||
|
|
||
| void setName () { | ||
| this.name = ConsoleReader.askProductName(); | ||
| } | ||
| void setPrice (){ | ||
| this.price = ConsoleReader.askProductPrice(); | ||
| } | ||
| } |
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.
Думаю, что данный класс можно расширить и включить в него методы и поля, которые сейчас находятся в Main, а конкретные математические операции вынести в отдельный класс Calculator. Этот тогда лучше будет переименовать, например, в SplitBill, BillSplitter или нечто подобное, отражающее его цель
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.
Внёс изменения. Создал класс Bill, описывающий счёт и его основные параметры
;
Работу со считыванием данных вынес в класс ConsoleReader;
По твоему совету мат. операции перенс в класс Calculator;