Skip to content
Open

1 #1

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

int friendsCount;
public class Calculator {
public static float calculate() {
Scanner console = new Scanner(System.in);
float sum=0.00f;

String cart = "Добавленные товары:";
double totalPrice = 0;
System.out.println("Введите товар");
String product = console.nextLine();
float price = priceChecking();
sum=sum+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.

Можно использовать сокращенную конструкцию sum += price;

String cheque = String.format("*********************************************\nДобавленные товары:\n" + product + " %.2f", price) + " " + FormOfCurrency.defineTheForm((int)Math.floor(price));
System.out.println("Товар успешно добавлен. Завершить? (Введите Завершить либо любой другой символ для продолжения)");

Calculator(int friendsCount) {
this.friendsCount = friendsCount;
while(true) {
if (console.next().equalsIgnoreCase("Завершить")) {
System.out.println(cheque);
break;
}
else {
System.out.println("Введите товар");
console.nextLine();
product = console.nextLine();
price = priceChecking();
sum=sum+price;
cheque = String.format(cheque + "\n" + product + " %.2f", price) + " " + FormOfCurrency.defineTheForm((int)Math.floor(price));
System.out.println("Товар успешно добавлен. Завершить? (Введите Завершить либо любой другой символ для продолжения)");
}
}
return sum;
}

void addItem(Item item) {
totalPrice += item.price;
cart = cart + "\n" + item.name;
public static float priceChecking () {
System.out.println("Введите цену товара в формате 00,00 (рубли,копейки)");
float price;
Scanner console = new Scanner(System.in);

System.out.println(item.name + " в корзине");
}
while (!(console.hasNextFloat())) {
System.out.println("Требуется именно число в формате 00,00 (рубли,копейки) или 00 (рубли)");
console.next();
}
price=console.nextFloat();

while (!(price > 0)) {
System.out.println("Стоимость товара должна быть больше нуля");
price=console.nextFloat();
}

double divideSum() {
return totalPrice / friendsCount;
return price;
}
}
18 changes: 18 additions & 0 deletions src/main/java/FormOfCurrency.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import java.util.*;

public class FormOfCurrency {
public static String defineTheForm(int count) {
String form;
if (count%100>4 && count%100<21) {
form = "рублей";
}
else if (count%10==1) {
form = "рубль";
}
else if (count%10>1 && count%10<5) {
form = "рубля";
}
else form = "рублей";

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

return form;
}
}
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.

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

import java.util.*;
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("Привет! Это программа Калькулятор счёта");
int guestCount = Request.askGuestCount(); // Метод запроса и проверки корректности количества гостей
System.out.println("Итак, количество гостей - " + guestCount+ " чел.");

System.out.println("Введите стоимость товара в формате: 'рубли.копейки' [10.45, 11.40]");
double price = scanner.nextDouble();
float sum = Calculator.calculate(); // Сбор позиций и цен чека, возврат суммы
String newline = "*********************************************";

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

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

if (answer.equalsIgnoreCase("Завершить")) {
break;
}
}
System.out.println(newline);
System.out.println(String.format("Общая сумма товаров - " + "%.2f", sum)+" " +FormOfCurrency.defineTheForm((int)Math.floor(sum)));
System.out.println(String.format("Сумма покупок на одного человека - " + "%.2f", (sum/guestCount))+ " " +FormOfCurrency.defineTheForm((int)Math.floor(sum/guestCount)));
System.out.println(newline);
}

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

System.out.println(calculator.cart);
System.out.println("Каждому человеку к оплате: " + formatter.roundResult(result) + " " + formatter.formatValue(result));
}
}
}
27 changes: 27 additions & 0 deletions src/main/java/Request.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import java.util.*;

public class Request {
public static int askGuestCount() {
System.out.println("Введите число гостей: ");
int count;
Scanner console = new Scanner(System.in);
while (true) {
if (!console.hasNextInt()) { // Проверем, что это целое число
System.out.println("Должно быть введено именно ЧИСЛО. Попробуем еще раз? )");
console.next();

} else {
count = console.nextInt();
if (count < 1)
System.out.println("Количество гостей должно быть больше 1 человека. Попробуем еще раз? )");
else {
if (count == 1) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

count < 1 и count < 1 можно объединить в count <= 1, без лишней вложенности

System.out.println("Количество гостей должно быть больше 1 человека. Попробуем еще раз? )");
} else
break;
}
}
}
return count;
}
}