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

public class Calculator {

private final HashMap<String, Double> goods = new HashMap<>();

public void addGoods() {
while (true) {
String command;
System.out.println("Добавить товар? Для окончания введите 'завершить'");
command = Main.scanner.nextLine();

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Попытка засчитана, но так тоже лучше не делать. Если прям нужно где-то считывать, то лучше передавать сканнер в параметрах.

if (command.equalsIgnoreCase("завершить")) {
break;
}
System.out.println("Введите стоимость товара например: '10.45'");
if (Main.scanner.hasNextDouble()) {
double price = Main.scanner.nextDouble();
storeGoods(command, price);
Main.scanner.nextLine();
} else {
System.out.println("Введено неверное значение");
Main.scanner.nextLine();
}
}
Main.scanner.close();

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.

Я это забыл удалить просто xD

}

private void storeGoods(String name, double price) {
if (goods.containsKey(name)) {
double calculated = goods.get(name) + price;
goods.put(name, calculated);
} else {
goods.put(name, price);
}
System.out.printf("Товар %s успешно добавлен%n", name);
}

public void printGoods() {
System.out.println("Добавленные товары:");
goods.forEach((k, v) -> System.out.printf(Locale.US, "%s %.2f%n", k, v));
}

public double getFinalSum(int numberOfPersons) {
return goods.values().stream().mapToDouble(Double::doubleValue).sum() / numberOfPersons;
}

}
48 changes: 47 additions & 1 deletion src/main/java/Main.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,52 @@
import java.util.Locale;
import java.util.Scanner;

public class Main {

private static int numberOfPersons = 0;
public static final Scanner scanner = new Scanner(System.in);
private static final String GREETING_MESSAGE = "Введите число на сколько человек разделить счет:";

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Здорово, что вынес текст в константу.


public static void main(String[] args) {
System.out.println("Hello world!");

scanner.useLocale(Locale.US);
printMessage(GREETING_MESSAGE);
applyNumberOfPersons();

Calculator calculator = new Calculator();
calculator.addGoods();
calculator.printGoods();

double sum = calculator.getFinalSum(numberOfPersons);

MoneyHelper moneyHelper = new MoneyHelper();
String rubbles = moneyHelper.getCurrencyCase(sum);

System.out.printf(Locale.US, "Сумма к оплате на персону: %.2f %s", sum, rubbles);

}

public static void printMessage(String message) {
System.out.println(message);
}

public static void applyNumberOfPersons() {
while (numberOfPersons <= 1) {
if (scanner.hasNextInt()) {
numberOfPersons = scanner.nextInt();
} else {
System.out.println("Введены некорректные данные, введите целое число");
scanner.next();
continue;
}
if (numberOfPersons < 1) {
System.out.println("Введено некорректное число персон. Введите целое число больше одного");
} else if (numberOfPersons == 1) {
System.out.println("Вы ввели 1, значит ели один, нет смысла делить счёт. Введите число больше одного");
} else {
System.out.println("Количество персон: " + numberOfPersons);
}
}
scanner.nextLine();
}
}
20 changes: 20 additions & 0 deletions src/main/java/MoneyHelper.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
public class MoneyHelper {

public String getCurrencyCase(double sum) {

int intSum = (int) Math.floor(sum);

var preLastDigit = intSum % 100 / 10;
if (preLastDigit == 1) {
return "рублей";
}

return switch (intSum % 10) {
case 1 -> "рубль";
case 2, 3, 4 -> "рубля";
default -> "рублей";
};

}

}