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

public class BillDivider {
private final String INT_REGEX = "\\b(?<!\\.)\\d+(?!\\.)\\b";
private final String DOUBLE_REGEX = "\\d*\\.\\d{2}";
private int userCount;
private List<Item> itemList = new ArrayList<>();
private Scanner scanner = new Scanner(System.in);
PluralHelper pluralRubles = new PluralHelper("Рублю", "Рубля", "Рублей");
PluralHelper pluralGuests = new PluralHelper("гость", "гостя", "гостей");
public void createAndSplitBill() {
getUserCount();
requestItems();
intermediateResult();
splitBill();
}
private void getUserCount() {
this.userCount = readIntUntilValid("Введите кол-во человек: ");
}
private int readIntUntilValid(String requestMessage) {
System.out.print(requestMessage);
String value = scanner.nextLine();
boolean isValidValue = value.matches(INT_REGEX) && Integer.parseInt(value) > 1;

while (!isValidValue) {
System.out.println("Ошибка, введено неверное значение, попробуйте снова...");
System.out.print(requestMessage);

value = scanner.nextLine();
isValidValue = value.matches(INT_REGEX) && Integer.parseInt(value) > 1;
}

return Integer.parseInt(value);
}
private void requestItems() {
String input = "";
while (!input.equalsIgnoreCase("Завершить")) {
addItem(requestItem());
System.out.println("Желаете добавить еще один товар?\nВведите \"Завершить\", если хотите закончить добавление.");
input = scanner.nextLine();
}
}
private void addItem(Item newItem) {
itemList.add(newItem);

String newItemName = newItem.getName();
String line = "~".repeat(47 + newItemName.length());

System.out.println(line);
System.out.printf("Товар \"%s\", стоимостью %s успешно добавлен!%n", newItemName, pluralRubles.getFormattedPluralPattern(newItem.getPrice(), "%.2f %s"));
System.out.println(line);
}
private Item requestItem() {
String name = readStringUntilValid("Введите название товара: ");
double price = readDoubleUntilValid("Введите Стоимость (в формате рубли.копейки): ");
return new Item(name, price);
}
private String readStringUntilValid(String requestMessage) {
System.out.print(requestMessage);
String value = scanner.nextLine();

while (value.trim().isEmpty()) {
System.out.println("Ошибка, введено неверное значение, попробуйте снова...");
System.out.print(requestMessage);
value = scanner.nextLine();
}

return value;
}
private double readDoubleUntilValid(String requestMessage) {
System.out.print(requestMessage);
String value = scanner.nextLine();

while (!value.matches(DOUBLE_REGEX)) {
System.out.println("Ошибка, введено неверное значение, попробуйте снова...");
System.out.print(requestMessage);
value = scanner.nextLine();
}

return Double.parseDouble(value);
}
private void intermediateResult() {
int tabSpace = Math.max(15, Collections.max(itemList.stream().map(Item::getName).toList(), Comparator.comparing(String::length)).length());
String lineCurve = "~".repeat(tabSpace * 2 + 7);
String linePlain = "-".repeat(tabSpace * 2 + 7);

System.out.println(lineCurve);
System.out.println(pluralGuests.getFormattedPluralPattern(userCount, "Общий чек на %.0f %s"));
System.out.println(lineCurve);
System.out.println("Добавленные товары:");
System.out.println(lineCurve);
System.out.printf("| %-" + tabSpace + "s | %-" + tabSpace + "s |%n", "Название товара", "Стоимость");
System.out.println(linePlain);
for (Item item : itemList) {
System.out.printf("| %-" + tabSpace + "s | %-" + tabSpace + "s |%n", item.getName(), pluralRubles.getFormattedPluralPattern(item.getPrice(), "%.2f %s"));
}
System.out.println(linePlain);
}
private void splitBill() {
double perGuest = itemList.stream().map(Item::getPrice).reduce(0.0, Double::sum) / userCount;
System.out.println(pluralRubles.getFormattedPluralPattern(perGuest, "Каждый должен заплатить по %.2f %s"));
}
}
35 changes: 35 additions & 0 deletions src/main/java/Item.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import java.util.List;
import java.util.Objects;

public class Item {
private final String name;
private final double price;

public Item(String name, double price) {
this.name = name;
this.price = price;
}

public String getName() {
return name;
}

public double getPrice() {
return price;
}


@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof Item otherItem)) { return false; }
return otherItem.name.equals(this.name) && (otherItem.price == this.price);
}

@Override
public int hashCode() {
return Objects.hash(this.name, this.price);
}
}
4 changes: 3 additions & 1 deletion src/main/java/Main.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import java.util.Scanner;

public class Main {
public static void main(String[] args) {
System.out.println("Hello world!");
BillDivider divider = new BillDivider();
divider.createAndSplitBill();
}
}
23 changes: 23 additions & 0 deletions src/main/java/PluralHelper.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
public class PluralHelper {
private String one;
private String couple;
private String some;
public PluralHelper(String one, String couple, String some) {
this.one = one;
this.couple = couple;
this.some = some;
}
private String getStringFormattedPlurals(double count) {
int val = Math.abs((int)count) % 100;
int num = val % 10;
if (val > 10 && val < 20) return some;
if (num > 1 && num < 5) return couple;
if (num == 1) return one;
return some;
}

public String getFormattedPluralPattern(double count, String pattern) {
return String.format(pattern, count, getStringFormattedPlurals(count));
}

}