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.

123 changes: 123 additions & 0 deletions .idea/codeStyles/Project.xml

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

5 changes: 5 additions & 0 deletions .idea/codeStyles/codeStyleConfig.xml

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

6 changes: 6 additions & 0 deletions .idea/compiler.xml

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

18 changes: 18 additions & 0 deletions .idea/gradle.xml

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

9 changes: 9 additions & 0 deletions .idea/misc.xml

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

6 changes: 6 additions & 0 deletions .idea/vcs.xml

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"
29 changes: 16 additions & 13 deletions src/main/java/Calculator.java
Original file line number Diff line number Diff line change
@@ -1,22 +1,25 @@
class Calculator {

int friendsCount;
public class Calculator {
private int peopleNumber;
private double sum;
private String productList = "";

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

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

void addItem(Item item) {
totalPrice += item.price;
cart = cart + "\n" + item.name;
public void addProduct(Product product){
this.sum = this.sum + product.getPrice();
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Можно ещё обойтись без this. (хотя и такие варианты встречаются), а также использовать конструкцию sum += product.getPrice();

this.productList = this.productList.concat(product.getName() + "\n");
System.out.println("Товар " + product.getName() + " на сумму = " + product.getPrice() + " успешно добавлен");
}

System.out.println(item.name + " в корзине");
public void printProductList(){
System.out.println(this.productList);
}

double divideSum() {
return totalPrice / friendsCount;
public double calculateSumToPay(){
return sum / peopleNumber;
}

}
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.

101 changes: 68 additions & 33 deletions src/main/java/Main.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,46 +4,81 @@ public class Main {

public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int personNumber = getPersonNumber();
double sumToPay;

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) {
// Создается калькулятор
Calculator calculator = new Calculator(personNumber);
// Пользователь вводит наименование и стоимость товара для подсчета
boolean stopEnterProduct = false;
boolean stopEnterPrice = false;
while (!stopEnterProduct){
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Можно ещё сделать бесконечный цикл while(true), а в if(productName.equalsIgnoreCase("завершить")) выходить из цикла при помощи break. Тогда отпадет необходимость дальнейшие действия заворачивать в else + не будем создавать дополнительную переменную stopEnterProduct.

System.out.println("Введите название товара");
String name = scanner.next();
if (scanner.hasNextLine()){
String productName = scanner.nextLine();
if(productName.equalsIgnoreCase("завершить")){
stopEnterProduct = true;
} else {
// Пользователь вводит стоимость товара для подсчета
while (!stopEnterPrice){
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Также можно сделать бесконечный цикл

System.out.println("Введите стоимость товара в рублях");
if(scanner.hasNextDouble()){
double productPrice = scanner.nextDouble();
if (productPrice < 0){
System.out.println("Некорректное значение");
continue;
}
Product product = new Product(productName, productPrice);
calculator.addProduct(product);
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Можно добавлять в список сразу при добавлении в список:
calculator.addProduct(new Product(productName, productPrice));

scanner.nextLine();
stopEnterPrice = true;
} else {
if (scanner.nextLine().equalsIgnoreCase("завершить")) {
stopEnterPrice = true;
} else{
System.out.println("Некорректное значение");
}

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

Choose a reason for hiding this comment

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

Имеет смысл выносить такие большие логические фрагменты в отдельные методы по примеру метода getPersonNumber(). Это делает программу больше удобочитаемой, когда разнородная логика не смешивается в один сплошной код.

calculator.printProductList();

calculator.addItem(new Item(name, price));
sumToPay = calculator.calculateSumToPay();

System.out.println(
"Хотите добавить еще один товар? Введите любой символ для продолжения, либо 'Завершить' если больше нет товаров для добавления");
String answer = scanner.next();
if (Math.floor(sumToPay) == 1)
System.out.println(String.format("Каждый должен заплатить по %.2f рубль",sumToPay));
else if (Math.floor(sumToPay) == 2 || Math.floor(sumToPay) == 3 || Math.floor(sumToPay) == 4)
System.out.println(String.format("Каждый должен заплатить по %.2f рубля",sumToPay));
else
System.out.println(String.format("Каждый должен заплатить по %.2f рублей",sumToPay));
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Строка ""Каждый должен заплатить по %.2f" встречается несколько раз в программе, имеет смысл вынести её в отдельную переменную и затем к ней прибавлять рубли в нужном виде. Основное преимущество такого подхода - при необходимости поменять текст надо будет поменять только текст в переменной без риска что-нибудь забыть

}

if (answer.equalsIgnoreCase("Завершить")) {
break;
public static int getPersonNumber(){
// Запрашиваем у пользователя количество человек, на которых нужно разделить счет
Scanner scanner = new Scanner(System.in);
int personNumber;
while (true){
System.out.println("На скольких человек нужно разделить счет?");
if(scanner.hasNextInt()){
personNumber = scanner.nextInt();
if (personNumber == 1){
System.out.println("Нет смысла что то считать и делить");
}
else if (personNumber < 1){
System.out.println("Некорректное значение для подсчета");
}
else {
return personNumber;
}
} else{
System.out.println("Некорректное значение для подсчета");
scanner.nextLine();
}
}

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

System.out.println(calculator.cart);
System.out.println("Каждому человеку к оплате: " + formatter.roundResult(result) + " " + formatter.formatValue(result));
}
}
}
16 changes: 16 additions & 0 deletions src/main/java/Product.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
public class Product {
// Описывает продук? который можно добавить для подсчета в калькулятор
private String name;
private double price;

public Product(String name, double price){
this.name = name;
this.price = price;
}
public String getName(){
return name;
}
public double getPrice(){
return price;
}
}