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
34 changes: 34 additions & 0 deletions src/main/java/Bill.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
public class Bill {
int numberOfPerson = 1; //Количество участников (по умолчанию 1)
String listOfProducts = ""; // Список продуктов в корзине
double sum = 0; // Стоимость всех продуктов в корзине

void setNumberOfPerson () {
this.numberOfPerson = ConsoleReader.askNumberOfPerson();
}
void addProduct (Product product) {
listOfProducts += String.format("%.2f руб. - %s\n", product.price, product.name);
sum += product.price;
System.out.printf("Товар \"%s\" стоимостью %.2f руб. добавлен в корзину.\n", product.name, product.price);
}
void printBill() {
System.out.printf("\nДобавленные товары:\n------\n%s------\n%.2f руб. - сумма всех товаров.\n\n", this.listOfProducts, this.sum);
}

// Метод выводит сообщение с долей каждого участника.
// Если сумма не может быть разделена поровну,
// считаем сколько должен заплатить каждый участник (в максимально равных долях).
void printParticipantAmount () {
double sumPerPerson = Calculator.getSumPerPerson(this);
double remOfDivision = Calculator.getRemOfDivision(this);
double lastParticipantPart = sumPerPerson + remOfDivision;

if (Calculator.getRemOfDivision(this) == 0)
System.out.printf("Счёт можно разделить поровну.\nКаждый должен заплатить по %.2f %s", sumPerPerson, Formatter.endOfRoubles(sumPerPerson));
else {
System.out.print("Счёт ровно не делится:");
System.out.printf("\n- доля %d из %d людей составит %.2f %s", numberOfPerson - 1, numberOfPerson, sumPerPerson, Formatter.endOfRoubles(sumPerPerson));
System.out.printf("\n- доля одного составит %.2f %s\n", lastParticipantPart, Formatter.endOfRoubles(lastParticipantPart));
}
}
}
12 changes: 12 additions & 0 deletions src/main/java/Calculator.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
public class Calculator {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Думаю, что данный класс можно расширить и включить в него методы и поля, которые сейчас находятся в Main, а конкретные математические операции вынести в отдельный класс Calculator. Этот тогда лучше будет переименовать, например, в SplitBill, BillSplitter или нечто подобное, отражающее его цель

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.

Внёс изменения. Создал класс Bill, описывающий счёт и его основные параметры
;
Работу со считыванием данных вынес в класс ConsoleReader;
По твоему совету мат. операции перенс в класс Calculator;

static double getSumPerPerson(Bill bill){
return Math.round(bill.sum / bill.numberOfPerson * 100) / 100.0;
}
static double getRemOfDivision(Bill bill) {
double sumPerPerson = Calculator.getSumPerPerson(bill);
return Math.round((bill.sum - sumPerPerson * bill.numberOfPerson) * 100) / 100.0;
}
static double roundDouble (Double d) {
return Math.round(d * 100) / 100d;
}
}
62 changes: 62 additions & 0 deletions src/main/java/ConsoleReader.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
import java.util.Locale;
import java.util.Scanner;

// TODO ToDo: нужно добавить обработку переполнений при считывании числовых значений и выполнении математических операций.

public class ConsoleReader {

public static Scanner scanner = new Scanner(System.in);
static int askNumberOfPerson () {
int numberOfPerson;
do {
System.out.println("Укажите количество людей (шт.): ");
while (!scanner.hasNextInt()) {
scanner.next();
System.err.print("Нужно ввести число.\n");
System.out.println("Укажите количество людей (шт.): ");
}
numberOfPerson = scanner.nextInt();
if (numberOfPerson <= 1) {
System.err.println("Количество должно быть больше 1");
} else {
return numberOfPerson;
}
} while (true);
}
static String askProductName () {
String name;
System.out.println("Введите название товара:");
name = scanner.next();
return name;
}
static double askProductPrice () {
scanner.useLocale(Locale.US);
double price;
do {
System.out.println("Введите стоимость в формате \"руб.коп\":");
while (!scanner.hasNextDouble()){
scanner.next();
System.err.println("Не верный формат значения.");
System.out.println("Введите стоимость в формате \"руб.коп\":");
}
price = scanner.nextDouble();
if (Calculator.roundDouble(price) <= 0) {
System.err.println("Стоимость должна быть больше нуля.");
} else {
return Calculator.roundDouble(price);
}

} while (true);
}
static boolean askToAddProduct(){
System.out.println("\nДобавить ещё один товар?\n\"Да (или любой символ)\" - добавить товар,\n\"Завершить\" - закончить ввод и посчитать сумму.");
if (scanner.next().equalsIgnoreCase("Завершить")) {
return true;
} else {
return false;
}
}
static void scannerClose (){
scanner.close();
}
}
16 changes: 16 additions & 0 deletions src/main/java/Formatter.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
public class Formatter {

// Метод возвращает слово "рубль" с окончанием, в зависимости от суммы.
static String endOfRoubles (double sum) {
int intSum = (int) Math.floor(sum);
if (intSum >= 10 && intSum <= 14)
return "рублей.";
else
return switch (intSum - 10 * (intSum / 10)) {
case 1 -> "рубль.";
case 2, 3, 4 -> "рубля.";
case 5, 6, 7, 8, 9, 0 -> "рублей.";
default -> "руб.";
};
}
}
18 changes: 16 additions & 2 deletions src/main/java/Main.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,20 @@

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

Bill bill = new Bill();
bill.setNumberOfPerson();

while (true) {
Product product = new Product();
product.setName();
product.setPrice();
bill.addProduct(product);
if (ConsoleReader.askToAddProduct()) {
bill.printBill();
bill.printParticipantAmount();
ConsoleReader.scannerClose();
break;
}
}
}
}
11 changes: 11 additions & 0 deletions src/main/java/Product.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
public class Product {
String name; // Название продукта
double price; // Цена продукта

void setName () {
this.name = ConsoleReader.askProductName();
}
void setPrice (){
this.price = ConsoleReader.askProductPrice();
}
}