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


Choose a reason for hiding this comment

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

Импорты от класса принято разделять 1 пустой строкой

public class Calculator {
private ArrayList<Item> items;
private int numberOfPeople;

public Calculator() {
items = new ArrayList<>();
}

public void start() {
inputNumberOfPeople();
inputItems();
printItems();
printAmountPerPerson();
}

private void inputNumberOfPeople() {
Scanner scanner = new Scanner(System.in);

Choose a reason for hiding this comment

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

Лучше вынести сканер на уровень класса и его использовать везде, а не создавать в каждом методе новый

boolean validInput = false;
while (!validInput) {
System.out.println("На сколько человек необходимо разделить счёт:");
String input = scanner.nextLine().trim();
if (input.matches("\\d+")) {
numberOfPeople = Integer.parseInt(input);
if (numberOfPeople <= 1) {
System.out.println("Ошибка: Введите корректное количество гостей, больше 1.");
} else {
validInput = true;
}
} else {
System.out.println("Ошибка: Введите целое число.");
}
}
}

private void inputItems() {
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("Введите название товара и его стоимость в формате 'название стоимость': например, пиво 58.99\nЛибо введите команду 'Завершить' для того, чтобы завершить процесс добавления товаров.");
String line = scanner.nextLine().trim();
if (line.equalsIgnoreCase("завершить")) {

Choose a reason for hiding this comment

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

Стоп-слово завершить можно вынести на уровень класса, чтобы если вдруг его пришлось менять - тебе не придется бегать по коду и искать его во всех файлах

break;
}

String[] parts = line.split(" ");
if (parts.length != 2 || !isValidPrice(parts[1])) {
System.out.println("Ошибка: Некорректный формат ввода или некорректная сумма товара.");
continue;
}

String name = parts[0];
double price = Double.parseDouble(parts[1].replace(',', '.'));

items.add(new Item(name, price));
System.out.println("Товар успешно добавлен.");
System.out.println("Хотите добавить еще один товар?");
}
}

private void printItems() {
System.out.println("Добавленные товары:");
for (Item item : items) {
System.out.println(item.getName() + " - " + item.getPrice());
}
}

private void printAmountPerPerson() {
double total = 0;
for (Item item : items) {
total += item.getPrice();
}
double perPerson = total / numberOfPeople;

String rublesString = Formatter.formatRubles(perPerson);

System.out.println("Каждый человек должен заплатить: " + rublesString);
}

private boolean isValidPrice(String priceStr) {
try {
String normalizedPrice = priceStr.replace(',', '.');
double price = Double.parseDouble(normalizedPrice);
return price >= 0;
} catch (NumberFormatException e) {
return false;
}
}
}
17 changes: 17 additions & 0 deletions src/main/java/Formatter.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
public class Formatter {
public static String formatRubles(double amount) {
int rubles = (int) amount;
int kopecks = (int) Math.round((amount - rubles) * 100);

String rublesString;
if (rubles % 10 == 1 && rubles % 100 != 11) {
rublesString = "рубль";
} else if (rubles % 10 >= 2 && rubles % 10 <= 4 && (rubles % 100 < 10 || rubles % 100 >= 20)) {
rublesString = "рубля";
} else {
rublesString = "рублей";
}

return rubles + " " + rublesString + " " + String.format("%02d", kopecks) + " копеек";
}
}
17 changes: 17 additions & 0 deletions src/main/java/Item.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
public class Item {
private String name;
private double price;

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

public String getName() {
return name;
}

public double getPrice() {
return 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 @@


public class Main {
public static void main(String[] args) {
System.out.println("Hello world!");
Calculator calculator = new Calculator();
calculator.start();
}
}