Repository navigation
Приложение "Калькулятор Счёта" #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
Lyoncheese
wants to merge
4
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
4 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,2 @@ | ||
| # Пустой репозиторий для работы с Java кодом в Android Studio | ||
| # «Калькулятор счёта» | ||
| Консольное приложение, которое будет задавать вопросы в консоли, считывать пользовательский ввод и в результате показывать список товаров и сумму для каждого из друзей. |
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,125 @@ | ||
| import java.util.InputMismatchException; | ||
| import java.util.Scanner; | ||
|
|
||
| public class Main { | ||
| public static double getDouble (Scanner scanner) { | ||
| try { | ||
| return scanner.nextDouble(); | ||
| } | ||
| catch (InputMismatchException e) { | ||
| scanner.next(); | ||
| return 0; | ||
| } | ||
| } | ||
| public static int getInt (Scanner scanner) { | ||
| try { | ||
| return scanner.nextInt(); | ||
| } | ||
| catch (InputMismatchException e) { | ||
| scanner.next(); | ||
| return 0; | ||
| } | ||
| } | ||
| public static class Formatter { | ||
| void printWithRubles (double x) { | ||
| int cutPoint = (int) Math.floor(x); | ||
| int rest = cutPoint % 10; | ||
| int rest1 = cutPoint % 100; | ||
| if (rest1 >= 10 && rest1 <= 19) { | ||
| System.out.printf("%.2f Рублей", x); | ||
| } | ||
| else if (rest == 0 || rest >= 5) { | ||
| System.out.printf("%.2f Рублей", x); | ||
| } | ||
| else if (rest == 1) { | ||
| System.out.printf("%.2f Рубль", x); | ||
| } | ||
| else if (rest >= 2) { | ||
| System.out.printf("%.2f Рубля", x); | ||
| } | ||
| } | ||
| } | ||
| public static class Product { | ||
| String name; | ||
| double price; | ||
|
|
||
| Product(String productName, double productPrice) { | ||
| name = productName; | ||
| price = productPrice; | ||
| } | ||
| } | ||
| public static class Calculator { | ||
| String productNames = ""; | ||
| double productPrices = 0; | ||
|
|
||
| void addProduct(Product p) { | ||
| productPrices = productPrices + p.price; | ||
| productNames = productNames.concat(p.name).concat("\n"); | ||
| System.out.println("Товар успешно добавлен!"); | ||
| } | ||
|
|
||
| double divideByAll (int guests) { | ||
| return productPrices / guests; | ||
| } | ||
| } | ||
|
|
||
| public static int getGuests(Scanner scanner) { | ||
| int guests; | ||
| while (true) { | ||
| System.out.println("На сколько человек необходимо разделить счёт?"); | ||
| guests = getInt(scanner); | ||
| if (guests > 1) { | ||
| break; | ||
| } else if (guests == 1) { | ||
| System.out.println("нет смысла ничего считать и делить"); | ||
| } else { | ||
| System.out.println("Это некорректное значение для подсчёта"); | ||
| } | ||
| } | ||
| return guests; | ||
| } | ||
|
|
||
| public static void getProducts(Scanner scanner, Calculator calc) { | ||
| while (true) { | ||
| System.out.println("Введите наименование товара или 'Завершить'"); | ||
| String productName = scanner.next(); | ||
| if (productName.equalsIgnoreCase("завершить")) { | ||
| break; | ||
| } | ||
| else { | ||
| while (true) { | ||
| System.out.println("Введите стоимость товара"); | ||
| double productPrice = getDouble(scanner); | ||
| if (productPrice > 0) { | ||
| Product newProduct = new Product(productName, productPrice); | ||
| calc.addProduct(newProduct); | ||
| break; | ||
| } | ||
| else { | ||
| System.out.println("Это некорректное значение для подсчёта"); | ||
| } | ||
| } | ||
| } | ||
| } | ||
| } | ||
|
|
||
| public static void main(String[] args) { | ||
| System.out.println("Hello world!"); | ||
| Scanner scanner = new Scanner(System.in); | ||
| int guests = getGuests(scanner); | ||
|
|
||
| Calculator calc = new Calculator(); | ||
| getProducts(scanner, calc); | ||
|
|
||
| System.out.println("Добавленные товары:"); | ||
| System.out.println(calc.productNames); | ||
| double result = calc.divideByAll(guests); | ||
| System.out.print("Каждый должен заплатить по: "); | ||
|
|
||
| Formatter f = new Formatter(); | ||
| f.printWithRubles(result); | ||
|
|
||
| scanner.close(); | ||
| } | ||
| } | ||
| } | ||
|
|
||
|
|
||
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.
Такие отдельные логические блоки, как этот (ввод и обработка количества людей), а также логические блоки с вводом товаров и выводом результатов лучше выносить в отдельные методы и затем вызывать их там, где необходимо. Это позволяет улучшить читаемость кода, т.к. разнородная логика не смешивается в один сплошной код, а также упрощает поддержку кода.