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
3 changes: 3 additions & 0 deletions .idea/.gitignore

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

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

public class AskInfo {
int peopleAmount;
double checkCount;
StringBuilder productList;

AskInfo() {
productList = new StringBuilder();
}

void askPeopleAmount() {
Scanner scanner = new Scanner(System.in);
boolean exceptionHappened;
while (true) {
exceptionHappened = false;
System.out.println("Введите количество гостей:");
try {
peopleAmount = scanner.nextInt();
}
catch (java.util.InputMismatchException e) {
System.out.println("Ошибка ввода, попробуйте еще раз.");
scanner.nextLine();
exceptionHappened = true;
}

if (!exceptionHappened && peopleAmount <= 1) {
System.out.println("Ошибка ввода количества гостей. Количество гостей должно быть больше 1.");
} else if (!exceptionHappened){
break;
}
}
}

void addProductsNameAndPrice() {
String productName;
double price = 0;
boolean exceptionHappened;
Scanner scanner = new Scanner(System.in);

while (true) {
System.out.println("Введите название товара:\nЕсли хотите вывести счет введите: Завершить.");
productName = scanner.next();

if (!productName.equalsIgnoreCase("Завершить")) {
productList.append(productName).append("\n");
}
else {
break;
}

while (true) {
exceptionHappened = false;
System.out.println("Введите цену товара:");
try {
price = scanner.nextDouble();
}
catch (java.util.InputMismatchException e) {
System.out.println("Ошибка ввода. Возможно неверный формат ввода. Повторите ввод.");
scanner.nextLine();
exceptionHappened = true;
}
if (price >= 0 && !exceptionHappened){
checkCount += price;
break;
}
else if (!exceptionHappened) {
System.out.println("Ошибка ввода. Цена не может быть меньше нуля. Повторите ввод.");
}
}
}
}
}
27 changes: 9 additions & 18 deletions src/main/java/Calculator.java
Original file line number Diff line number Diff line change
@@ -1,22 +1,13 @@
class Calculator {
public class Calculator {
double value;
int divider;

int friendsCount;

String cart = "Добавленные товары:";
double totalPrice = 0;

Calculator(int friendsCount) {
this.friendsCount = friendsCount;
}

void addItem(Item item) {
totalPrice += item.price;
cart = cart + "\n" + item.name;

System.out.println(item.name + " в корзине");
Calculator(double value, int divider) {
this.value = value;
this.divider = divider;
}

double divideSum() {
return totalPrice / friendsCount;
double division() {
return value / divider;
}
}
}
28 changes: 28 additions & 0 deletions src/main/java/FormatToRubles.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
public class FormatToRubles {
double rubbles;

FormatToRubles(double rubbles) {
this.rubbles = rubbles;
}

String formatRubbles() {
int rubleOrRubles;
rubleOrRubles = (int) Math.floor(rubbles);
String checkMessage = null;

if (rubleOrRubles <= 1) {
checkMessage = "С человека по %.2f рубль";
checkMessage = String.format(checkMessage,rubbles );

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Код checkMessage = String.format(checkMessage,rubbles ); повторяется в каждой ветке, можно его вынести после if-else, и часть с "С человека по %.2f ..."; тоже

} else if (rubleOrRubles < 9) {
checkMessage = "С человека по %.2f рубля";
checkMessage = String.format(checkMessage,rubbles );
} else if (rubleOrRubles >= 10) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Для полной обработки окончания нужно учесть, на что оканчивается число (можно использовать %10): 1 - "рубль", 2-4 - "рубля", 5-9 (и 0) - "рублей". Плюс учесть, что для чисел 11-19 - "рублей" (можно использовать %100)

checkMessage = "С человека по %.2f рублей";
checkMessage = String.format(checkMessage,rubbles );
}
return checkMessage;
}
}



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

This file was deleted.

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

This file was deleted.

64 changes: 20 additions & 44 deletions src/main/java/Main.java
Original file line number Diff line number Diff line change
@@ -1,49 +1,25 @@
import java.util.Scanner;

public class Main {

public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

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

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

Calculator calculator = new Calculator(friendCount);

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

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

calculator.addItem(new Item(name, price));

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

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

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

System.out.println(calculator.cart);
System.out.println("Каждому человеку к оплате: " + formatter.roundResult(result) + " " + formatter.formatValue(result));
// Собираю вводные данные
AskInfo askPeople = new AskInfo();
askPeople.askPeopleAmount();
askPeople.addProductsNameAndPrice();

//Произвожу вычисления
Calculator calculator = new Calculator(askPeople.checkCount, askPeople.peopleAmount);
double calculatedCheck = calculator.division();

//Вывожу список товаров
ShowProductList showProductList = new ShowProductList(askPeople.productList);
showProductList.printProductList();

//Форматирую окончание слова рубль для сообщения
FormatToRubles formatToRubles = new FormatToRubles(calculatedCheck);
String checkMessage = formatToRubles.formatRubbles();

//Вывожу сколько должен заплатить каждый гость
ShowFinalCheck showFinalCheck = new ShowFinalCheck(checkMessage);
showFinalCheck.printFinalCheck();
}
}
12 changes: 12 additions & 0 deletions src/main/java/ShowFinalCheck.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
public class ShowFinalCheck {
String priceMessage;

ShowFinalCheck(String priceMessage) {
this.priceMessage = priceMessage;
}

void printFinalCheck() {
System.out.println(priceMessage);
}

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

ShowProductList(StringBuilder productList) {
this.productList = productList;
}

void printProductList(){
System.out.println(productList);
}
}