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
27 changes: 27 additions & 0 deletions src/main/java/CalculationResult.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import java.util.List;

public class CalculationResult {

private final List<String> goodList;
private final float pricePerPerson;
private final String currencySuffix;

public CalculationResult(List<String> goodList, float pricePerPerson, String currencySuffix) {
this.goodList = goodList;
this.pricePerPerson = pricePerPerson;
this.currencySuffix = currencySuffix;
}

public float getPricePerPerson() {
return pricePerPerson;
}

public List<String> getGoodList() {
return goodList;
}

public String getCurrencySuffix() {
return currencySuffix;
}
}

70 changes: 70 additions & 0 deletions src/main/java/Calculator.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
import java.io.BufferedReader;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

public class Calculator {

private static final String TERMINATE_COMMAND = "завершить";
private static final char PRICE_DELIMITER = '.';
private static final char MIN_DIGIT = '0';
private static final char MAX_DIGIT = '9';

private final BufferedReader reader;
private final int peopleCount;
private final PricePlurals formatter;

public Calculator(BufferedReader reader, int peopleCount, PricePlurals formatter) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

В конструктор лучше передавать то, чтобы необходимо снаружи класса передать внутрь класса для использования им. Если что-то можно и так создать внутри класса, то лучше так и сделать. Например, экземпляр BufferedReader можно создать внутри класса Calculator, PricePlurals сделать static

this.reader = reader;
this.peopleCount = peopleCount;
this.formatter = formatter;
}

public CalculationResult calculate() throws IOException {
final List<String> goodList = new LinkedList<>();
float totalPrice = 0F;
while (true) {
System.out.println("Введите наименование товара");
final String good = reader.readLine();
float price = 0F;
while (price <= 0) {
System.out.println("Введите цену товара. Число должно быть положительным.");
final String potentialPrice = reader.readLine();
if (isNotValidPrice(potentialPrice)) {
System.out.println("Цена введена неправильно. Разрешены только цифры и формате 0,00 или 0 ");
continue;
}
price += Float.parseFloat(potentialPrice);
}
goodList.add(good);
totalPrice += price;
System.out.println("Товар успешно добален");
System.out.println("Напишите любой символ для добавления товара\n" + "или слово \"Завершить\" если хотите перейти к расчетам ");

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Такие подряд идущие println можно объединить в один.

final String command = reader.readLine();
if (TERMINATE_COMMAND.equalsIgnoreCase(command)) {
break;
}
}
System.out.println("Общая сумма составила "+ totalPrice +" руб.");
final float pricePerPerson = totalPrice / peopleCount;
final String currencySuffix = formatter.getSuffix(pricePerPerson);
return new CalculationResult(goodList, pricePerPerson, currencySuffix);
}

private boolean isNotValidPrice(String price) {
boolean dotIncluded = false;
final int length = price.length();
for (int i = 0; i < length; ++i) {
final char symbol = price.charAt(i);
if (symbol == PRICE_DELIMITER) {
if (dotIncluded) return true;
dotIncluded = true;
continue;
}
if (symbol < MIN_DIGIT || symbol > MAX_DIGIT) {
return true;
}
}
return false;
}
}
32 changes: 27 additions & 5 deletions src/main/java/Main.java
Original file line number Diff line number Diff line change
@@ -1,8 +1,30 @@
public class Main {
// dev branch for Y.Practicum
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;


public static void main(String[] args) {
// ваш код начнется здесь
// вы не должны ограничиваться только классом Main и можете создавать свои классы по необходимости
System.out.println("Привет Мир");
public class Main {
public static void main(String[] args) throws IOException {
try (final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) {
int peopleCount = 0;
int MIN_USER_COUNT=2;
while (peopleCount < MIN_USER_COUNT) {
System.out.println("Введите количество людей");
peopleCount = Integer.parseInt(reader.readLine());
if (peopleCount < MIN_USER_COUNT) {
System.out.println("Количество людей не может быть меньше " + MIN_USER_COUNT);
}
}
final PricePlurals formatter = new PricePlurals();

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Можно сделать метод у класса PricePlurals тоже static, как и его поля, чтобы не пришлось создавать единственный экземпляр класса для однократного использования

final Calculator calculator = new Calculator(reader, peopleCount, formatter);
final CalculationResult result = calculator.calculate();
System.out.println("Список товаров:");
for (final String good : result.getGoodList()) {
System.out.println(good);
}
final String formattedPrice = String.format("%.2f %s", result.getPricePerPerson(), result.getCurrencySuffix());
System.out.printf("Каждый участник должен заплатить %s%n", formattedPrice);
}
}
}
23 changes: 23 additions & 0 deletions src/main/java/PricePlurals.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
public class PricePlurals {

private static final int RADIX = 10;
private static final int REMAINDER_ONE = 1;
private static final int REMAINDER_TWO = 2;
private static final int REMAINDER_THREE = 3;
private static final int REMAINDER_FOUR = 4;
private static final int ELEVEN = 11;
private static final int TWELVE = 12;
private static final int THIRTEEN = 13;
private static final int FOURTEEN = 14;

public String getSuffix(float price) {
final int roundedPrice = (int) price;
final int lastDigit = roundedPrice % RADIX;
if (lastDigit == REMAINDER_ONE && roundedPrice != ELEVEN) return "рубль";
if (lastDigit == REMAINDER_TWO && roundedPrice != TWELVE) return "рубля";
if (lastDigit == REMAINDER_THREE && roundedPrice != THIRTEEN) return "рубля";
if (lastDigit == REMAINDER_FOUR && roundedPrice != FOURTEEN) return "рубля";
return "рублей";
}
}