Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion src/main/java/Main.java
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();
}
}
24 changes: 24 additions & 0 deletions src/main/java/calculator/Calculator.java
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;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Возможно вас учат венгерской раскладке, но сейчас никто так в андроид разработке не пишет.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

хорошо бы увидеть пример, как пишут) без префикса?

Copy link
Copy Markdown

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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()));

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Я бы наоборот, сравнивал введенную строку с твоей константой. Хотя это наверно скорее вкусовщина

mUserInteractor.printResult(mStringBuilder.toString(), totalSum/totalPersons);
}
}
19 changes: 19 additions & 0 deletions src/main/java/calculator/Product.java
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;
}
}
17 changes: 17 additions & 0 deletions src/main/java/calculator/RubleFormatter.java
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 -> "рублей";
};
}
}
104 changes: 104 additions & 0 deletions src/main/java/calculator/UserInteractor.java
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("Вы ошиблись при вводе, введите цену заново (копейки указывать через \".\"): ");
}
}

}

}