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
2 changes: 1 addition & 1 deletion settings.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,4 @@ dependencyResolutionManagement {
mavenCentral()
}
}
rootProject.name = "BillCalculator"
rootProject.name = "Java-Module-Project"
61 changes: 48 additions & 13 deletions src/main/java/Calculator.java
Original file line number Diff line number Diff line change
@@ -1,22 +1,57 @@
class Calculator {
import java.util.ArrayList;

int friendsCount;
public class Calculator {

String cart = "Добавленные товары:";
double totalPrice = 0;
public static int peopleCount;
private static final ArrayList<Good> basket = new ArrayList<>();

Calculator(int friendsCount) {
this.friendsCount = friendsCount;
public static void addNewGood(Good good) {
basket.add(good);
System.out.printf("Добавлен новый товар [" + good.goodLabel + "] стоимостью [%.2f] "
+ setRoubleCase(good.goodPrice) + "\n", good.goodPrice);
}

void addItem(Item item) {
totalPrice += item.price;
cart = cart + "\n" + item.name;
public static void printCheck() {
printGoods();
double totalPrice = getTotalPrice();
System.out.printf("Общая сумма: %.2f %s%n", totalPrice, setRoubleCase(totalPrice));
System.out.printf("Количество человек: %s%n", peopleCount);
double shareRatio = getShareRatio(totalPrice, peopleCount);
System.out.printf("Каждый должен заплатить: %.2f %s%n", shareRatio, setRoubleCase(shareRatio));
}

public static void printGoods() {
System.out.print("Добавленные товары:\n");
for (int i = 0; i < basket.size(); i++) {
System.out.printf("Товар [" + basket.get(i).goodLabel + "] стоимостью [%.2f] "
+ setRoubleCase(basket.get(i).goodPrice) + "\n", basket.get(i).goodPrice);
}
}

System.out.println(item.name + " в корзине");
public static double getTotalPrice() {
double totalPrice = 0;
for (int i = 0; i < basket.size(); i++) {
totalPrice = totalPrice + basket.get(i).goodPrice;
}
return totalPrice;
}

double divideSum() {
return totalPrice / friendsCount;
public static double getShareRatio(double totalPrice, double peopleCount) {
return totalPrice / peopleCount;
}

private static String setRoubleCase(double d) {

int n1 = (int) d % 100;
int n2 = n1 % 10;

if (n1 > 10 && n1 < 20) {
return "рублей";
}else if (n2 > 1 && n2 < 5) {
return "рубля";
}else if (n2 == 1) {
return "рубль";
}else
return "рублей";
}

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 - else if - else можно ещё заменить конструкцией switch-case

}
}
17 changes: 0 additions & 17 deletions src/main/java/Formatter.java

This file was deleted.

11 changes: 11 additions & 0 deletions src/main/java/Good.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
public class Good {

String goodLabel;
Double goodPrice;

Good(String goodLabel, Double goodPrice) {
this.goodLabel = goodLabel;
this.goodPrice = goodPrice;
}

}
10 changes: 0 additions & 10 deletions src/main/java/Item.java

This file was deleted.

89 changes: 62 additions & 27 deletions src/main/java/Main.java
Original file line number Diff line number Diff line change
@@ -1,49 +1,84 @@
import java.util.Scanner;


public class Main {

static Scanner scanner = new Scanner(System.in);

public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Добро пожаловать в систему совместных закупок!\n");
getPeopleCount();
getGoods();
Calculator.printCheck();
}

int friendCount;
while (true) {
System.out.println("На сколько человек необходимо разделить счет?");
friendCount = scanner.nextInt();
static void getPeopleCount() {
int peopleCount;

if (friendCount > 1) {
break;
} else if (friendCount == 1) {
System.out.println(
"Нет смысла делить сумму на одного человека. Давайте попробуем ввести другое значение, которое будет больше единицы.");
System.out.print("Сколько человек будет приобретать товары?\n");

while (true) {
if (scanner.hasNextInt()) {
int input = scanner.nextInt();
if (input >= 2) {
peopleCount = input;
break;
} else {
System.out.print("Ошибка: неверный ввод!\n");
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Можно убрать этот блок с else, выводить сообщение "Ошибка: неверный ввод!" в конце while вне всех if-else - так можно сократить и оптимизировать этот блок

} else {
System.out.println("Неверное количество друзей. Значение должно быть болье единицы, давайте попробуем еще раз.");
System.out.print("Ошибка: неверный ввод!\n");
scanner.next();
}
}
Calculator.peopleCount = peopleCount;
}

static void getGoods() {

Calculator calculator = new Calculator(friendCount);
String goodLabel;
double goodPrice;

System.out.print("Введите название товара:\n");
goodLabel = scanner.next();

while (true) {
System.out.println("Введите название товара");
String name = scanner.next();

System.out.println("Введите стоимость товара в формате: 'рубли.копейки' [10.45, 11.40]");
double price = scanner.nextDouble();
System.out.print("Введите стоимость товара [" + goodLabel + "] в формате: \"руб.коп\", например [10.45, 11.40]:\n");

while (true) {

if (scanner.hasNextDouble()) {
double input = scanner.nextDouble();
if (isRightFormat(input)) {
goodPrice = input;
break;
} else {
System.out.print("Ошибка: неверный ввод!\n");

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Строка "Ошибка: неверный ввод!\n" встречается несколько раз в программе, имеет смысл вынести её в отдельную переменную. Основное преимущество такого подхода - при необходимости поменять текст надо будет поменять только текст в переменной

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.

Понял, благодарю!

}
} else {
System.out.print("Ошибка: неверный ввод!\n");
scanner.next();
}
}

calculator.addItem(new Item(name, price));
Calculator.addNewGood(new Good(goodLabel, goodPrice));

System.out.println(
"Хотите добавить еще один товар? Введите любой символ для продолжения, либо 'Завершить' если больше нет товаров для добавления");
String answer = scanner.next();
System.out.print("Введите название товара, или введите \"Завершить\", чтобы закончить:\n");
String input = scanner.next();

if (answer.equalsIgnoreCase("Завершить")) {
if (input.equalsIgnoreCase("Завершить")) {
break;
} else {
goodLabel = input;
}
}

double result = calculator.divideSum();
Formatter formatter = new Formatter();
}
}

System.out.println(calculator.cart);
System.out.println("Каждому человеку к оплате: " + formatter.roundResult(result) + " " + formatter.formatValue(result));
static boolean isRightFormat (Double d) {
String[] splitter = String.valueOf(d).split("[.]");
int l = splitter[1].length();
return (d > 0) && (l <= 2);
}
}
}