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
Vegrow
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 |
|---|---|---|
| @@ -1,6 +1,12 @@ | ||
| import calculator.Calculator; | ||
| import calculator.RubleFormatter; | ||
| import calculator.UserInteractor; | ||
|
|
||
| public class Main { | ||
| public static void main(String[] args) { | ||
| System.out.println("Hello world!"); | ||
| RubleFormatter rubleFormatter = new RubleFormatter(); | ||
| UserInteractor userInteractor = new UserInteractor(System.in, System.out, rubleFormatter); | ||
| Calculator calculator = new Calculator(userInteractor); | ||
| calculator.start(); | ||
| } | ||
| } |
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,24 @@ | ||
| package calculator; | ||
|
|
||
| public class Calculator { | ||
|
|
||
| private final static String FINISH = "завершить"; | ||
| private final UserInteractor mUserInteractor; | ||
| private final StringBuilder mStringBuilder = new StringBuilder(); | ||
| private double totalSum; | ||
|
|
||
| public Calculator(UserInteractor userInteractor) { | ||
| mUserInteractor = userInteractor; | ||
| } | ||
|
|
||
| public void start() { | ||
| int totalPersons = mUserInteractor.requestGuestNumber(); | ||
| do { | ||
| Product product = mUserInteractor.requestProduct(); | ||
| mUserInteractor.showProductAddSuccessMessage(product); | ||
| totalSum += product.getCost(); | ||
| mStringBuilder.append(product.getName()).append("\n"); | ||
| } while (!FINISH.equalsIgnoreCase(mUserInteractor.requestString())); | ||
|
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. Я бы наоборот, сравнивал введенную строку с твоей константой. Хотя это наверно скорее вкусовщина |
||
| mUserInteractor.printResult(mStringBuilder.toString(), totalSum/totalPersons); | ||
| } | ||
| } | ||
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,19 @@ | ||
| package calculator; | ||
|
|
||
| public class Product { | ||
| private final String mName; | ||
| private final double mCost; | ||
|
|
||
| public Product(String name, double cost) { | ||
| mName = name; | ||
| mCost = cost; | ||
| } | ||
|
|
||
| public String getName() { | ||
| return mName; | ||
| } | ||
|
|
||
| public double getCost() { | ||
| return mCost; | ||
| } | ||
| } |
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,17 @@ | ||
| package calculator; | ||
|
|
||
| public class RubleFormatter { | ||
| public String getFormatterRubles(double amount) { | ||
| double roundedAmount = Math.floor(amount); | ||
| int preLastDigit = (int) (roundedAmount % 100 / 10); | ||
| if (preLastDigit == 1) { | ||
| return "рублей"; | ||
| } | ||
|
|
||
| return switch ((int) roundedAmount % 10) { | ||
| case 1 -> "рубль"; | ||
| case 2, 3, 4 -> "рубля"; | ||
| 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 |
|---|---|---|
| @@ -0,0 +1,104 @@ | ||
| package calculator; | ||
|
|
||
| import java.io.InputStream; | ||
|
|
||
| import java.io.PrintStream; | ||
| import java.util.Scanner; | ||
|
|
||
| public class UserInteractor { | ||
|
|
||
| /** | ||
| * Минимальное количество символов в названии позиции. | ||
| * Поскольку нигде не указано необходимое значение, взято число 2, т.к. интерфейс на русском, | ||
| * и автор ни разу не видел в чеке позицию из одной буквы, а вот про "щи" знает не понаслышке. | ||
| */ | ||
| private static final int MIN_PRODUCT_NAME_LENGTH = 2; | ||
| private final Scanner mScanner; | ||
| private final PrintStream mPrintStream; | ||
| private final RubleFormatter mRubleFormatter; | ||
|
|
||
| public UserInteractor(InputStream is, PrintStream ps, RubleFormatter rubleFormatter) { | ||
| mScanner = new Scanner(is); | ||
| mPrintStream = ps; | ||
| mRubleFormatter = rubleFormatter; | ||
| } | ||
|
|
||
| public int requestGuestNumber() { | ||
| int guestNumber; | ||
| mPrintStream.println("Введите количество человек: "); | ||
| while (true) { | ||
| try { | ||
| guestNumber = Integer.parseInt(mScanner.nextLine()); | ||
| if (guestNumber > 1) { | ||
| return guestNumber; | ||
| } else { | ||
| mPrintStream.println("Количество человек должно быть больше одного, повторите ввод: "); | ||
| } | ||
| } catch (Exception e) { | ||
| mPrintStream.println("Вы ошиблись при вводе, введите количество человек: "); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| public Product requestProduct() { | ||
| String name = requestProductName(); | ||
| double cost = requestProductCost(name); | ||
| return new Product(name, cost); | ||
| } | ||
|
|
||
| public void showProductAddSuccessMessage(Product product) { | ||
| mPrintStream.println("Позиция \"" + product.getName() + "\" успешно добавлена"); | ||
| } | ||
|
|
||
| public String requestString() { | ||
| mPrintStream.println("Хотите добавить ещё один товар? Введите ЗАВЕРШИТЬ завершения добавления и переходу к расчёту"); | ||
| return mScanner.nextLine(); | ||
| } | ||
|
|
||
| public void printResult(String products, double costForPerson) { | ||
| String rubbles = mRubleFormatter.getFormatterRubles(costForPerson); | ||
| mPrintStream.println("\n===================================================="); | ||
| mPrintStream.println("Добавленные товары:\n" + products); | ||
| mPrintStream.printf("Сумма с каждого: %.2f %s", costForPerson, rubbles); | ||
| mPrintStream.println("\n===================================================="); | ||
| } | ||
|
|
||
| /** | ||
| * Привет ревьюер, данный метод возвращает название товара. | ||
| * Поскольку точного тз нет, а разраб (т.е. я) вообще не в курсе, | ||
| * может ли название состоять из одних лишь букв или спецсимволов, то считаем, что может. | ||
| * | ||
| * @return название товара | ||
| */ | ||
| private String requestProductName() { | ||
| mPrintStream.println("Введите название товара: "); | ||
| String name; | ||
| while (true) { | ||
| name = mScanner.nextLine(); | ||
| if (name.length() >= MIN_PRODUCT_NAME_LENGTH) { | ||
| return name; | ||
| } else { | ||
| mPrintStream.println("Название товара не может быть пустым или состоять только из одной буквы, повторите ввод: "); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| private double requestProductCost(String productName) { | ||
| double cost; | ||
| mPrintStream.println("Введите цену для \"" + productName + "\":"); | ||
| while (true) { | ||
| try { | ||
| cost = Double.parseDouble(mScanner.nextLine()); | ||
| if (cost > 0) { | ||
| return cost; | ||
| } else { | ||
| mPrintStream.println("Цена должна быть больше нуля, повторите ввод: "); | ||
| } | ||
| } catch (Exception e) { | ||
| mPrintStream.println("Вы ошиблись при вводе, введите цену заново (копейки указывать через \".\"): "); | ||
| } | ||
| } | ||
|
|
||
| } | ||
|
|
||
| } |
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.
хорошо бы увидеть пример, как пишут) без префикса?
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.
Да, примерно вот так это выглядит
userInteractor
Можно почитать вот тут
https://ru.wikipedia.org/wiki/CamelCase
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.
И вот тут
https://ru.wikipedia.org/wiki/Соглашения_об_именах_(программирование)#Java