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"
38 changes: 22 additions & 16 deletions src/main/java/Calculator.java
Original file line number Diff line number Diff line change
@@ -1,22 +1,28 @@
class Calculator {
import java.util.Scanner;

int friendsCount;
public class Calculator {

String cart = "Добавленные товары:";
double totalPrice = 0;
public void 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.

Методы лучше стараться называть глаголами, а вот классы можно существительными

Products list = new Products();
double price = list.Price();
Guests Guests = new Guests();
int peopleAmount = Guests.peopleAmount();

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Поскольку peopleAmount и Price - статические методы, их можно вызывать так - Guests.peopleAmount() и Products.Price(), тогда переменные list и Guests не нужны


Calculator(int friendsCount) {
this.friendsCount = friendsCount;
double score = price / peopleAmount;
String finalPriсe = "Общая сумма составила %.2f ";
String Deal = "\nКаждый человек должен заплатить %.2f ";
System.out.println(String.format(finalPriсe, price) + endWord(price) + "." + String.format(Deal, score) + endWord(score) + ".");
}

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

System.out.println(item.name + " в корзине");
}

double divideSum() {
return totalPrice / friendsCount;
public String endWord(double a) {
int cur = (int) Math.floor(a);
if (cur % 100 > 5 && cur <= 20) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Во второй части сравнивать нужно тоже cur % 100

return "рублей";
} else if (cur % 10 == 1) {
return "рубль";
} else if (cur % 10 > 1 && cur % 10 < 5) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Выражение cur % 10 считается несколько раз, можно посчитать его один раз, записать в переменную и использовать ее

return "рубля";
}
return "рублей";
}
}
}
17 changes: 0 additions & 17 deletions src/main/java/Formatter.java

This file was deleted.

32 changes: 32 additions & 0 deletions src/main/java/Guests.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import java.util.Scanner;

public class Guests {
static int peopleAmount;
public static int peopleAmount()
{
return peopleAmount;
}
public static void guests(){
System.out.println("Добрейший вечерочек");
Scanner scanner = new Scanner(System.in);
System.out.println("На скольких человек разделить счет?");


while (true) {

if (scanner.hasNextInt()) {
peopleAmount = scanner.nextInt();
if (peopleAmount > 1) {
break;
}
if (peopleAmount <= 1) {
System.out.println("Некорректое число, пожалуйста введите число больше 1");
}
} else{
System.out.println("Некорректный запрос, пожалуйста введите число больше 1");
scanner.nextLine();

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

This file was deleted.

45 changes: 5 additions & 40 deletions src/main/java/Main.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,47 +3,12 @@
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();
Guests.guests();
Products.products();
Calculator cal=new Calculator();
cal.calculator();

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));
}
}

46 changes: 46 additions & 0 deletions src/main/java/Products.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import java.util.Scanner;

public class Products {

static double Price;
static double Price()

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

{
return Price;
}

public static void products() {
Scanner scanner = new Scanner(System.in);
String names = "";

while (true) {
System.out.println("Введите наименование товара:");
String name = scanner.next();
names += "Продукт: " + name + "." + " Стоимость: ";
double price;
while (true) {
System.out.println("Введите стоимость товара в формате \"рубли,копейки\":");
price = scanner.nextDouble();

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Пользователь может ввести на вопрос про стоимость товаров вместо числа строку. Для количества человек ты обрабатываешь такую ситуацию через hasNextInt, стоит добавить обработку и для стоимости


if (price <=0) {
System.out.println("Некорректное значение. Попробуйте еще раз.");
} else {
break;
}
}
names += price + ".\n";
Price += price;

System.out.println("Товар добавлен в список!");
System.out.println("Если хотите добавить еще товар, введите \"Да\".\nЕсли хотите завершить покупку, введите \"Завершить\".");
String add = scanner.next();
if (add.equalsIgnoreCase("да")) { }

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 пустое, можно этот if вообще убрать

if (add.equalsIgnoreCase("Завершить")) {
System.out.println("Добавленные товары:\n" + names);
break;
}
else;

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 тоже нет необходимости

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.

Извините не могу изменить рекомендательные микромоменты потому что я на ужасных стрессах от того факта что появились 2 непонятных для меня класса которых у меня никогда в жизни не было Formatter и Item. А у меня закрыт доступ ко 2рой проектной работе которую надо сделать за 2 дня и сдать

}

}

}