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


public class Calculator {
private ArrayList<Item> items;
private int numberOfPeople;
public Calculator() { items = new ArrayList<>();}

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

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

private void inputNumberOfPeople() {
Scanner scanner = new Scanner(System.in);
boolean validInput = false;
while (!validInput) {
System.out.println("На скольких человек необходимо разделить счёт:");
String inmput = scanner.nextLine().trim();
if (inmput.matches("\\d+")) {
numberOfPeople = Integer.parseInt(inmput);
System.out.println("На сколько человек необходимо разделить счёт:");
String input = scanner.nextLine().trim();
if (input.matches("\\d+")) {
numberOfPeople = Integer.parseInt(input);
if (numberOfPeople <= 1) {
System.out.println("Ошибка: Введите корректное количество гостей, больше одного.");
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Либо введите команду 'Завершить' для того, чтоб завершить процесс добавления товаров.");
System.out.println("Введите название товара и его стоимость в формате 'название стоимость': например, пиво 58.99\nЛибо введите команду 'Завершить' для того, чтобы завершить процесс добавления товаров.");
String line = scanner.nextLine().trim();
if (line.equalsIgnoreCase("завершить")) {
break;
}

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

String name = parts[0];
double price = Double.parseDouble(parts[1]);
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) {
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) {
String[] parts = priceStr.split("\\.");
if (parts.length !=2) {
try {
String normalizedPrice = priceStr.replace(',', '.');
double price = Double.parseDouble(normalizedPrice);
return price >= 0;
} catch (NumberFormatException e) {
return false;
}
if (!parts[0].matches("\\d+") || !parts[1].matches("\\d{2}")){
return false;
}
return true;
}
}
13 changes: 8 additions & 5 deletions src/main/java/Formatter.java
Original file line number Diff line number Diff line change
@@ -1,14 +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)) {
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;

return rubles + " " + rublesString + " " + String.format("%02d", kopecks) + " копеек";
}
}
}
12 changes: 9 additions & 3 deletions src/main/java/Item.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,12 @@ public Item(String name, double price) {
this.name = name;
this.price = price;
}
public String getName() {return name;}
public double getPrice() {return price;}
}

public String getName() {
return name;
}

public double getPrice() {
return price;
}
}
2 changes: 0 additions & 2 deletions src/main/java/Main.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,5 @@ public class Main {
public static void main(String[] args) {
Calculator calculator = new Calculator();
calculator.start();


}
}