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

public class Calculate {
float price;
int rubli;
String rublWord;
String productName = "";
float totalPrice;
String totalList = "";
String stopWord = "Завершить";
Scanner scanWords = new Scanner(System.in);
float finalPrice;

public void calculate(int howPeople) {
System.out.println("Какой товар Вы хотите добавить?");
productName = scanWords.next();
System.out.println("Введите стоимость продукта");
while (!productName.equalsIgnoreCase(stopWord)) {
Scanner scanPrice = new Scanner(System.in);
if (scanPrice.hasNextFloat() == false) {
System.out.println("Вы ввели неверную стоимость товара. Введите стоимость в виде цифр");
} else {
totalList = totalList + "\n" + productName;
price = scanPrice.nextFloat();
totalPrice = totalPrice + price;
System.out.println("Вы успешно добавили товар " + productName + " стоимостью: " + 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.

Тут лучше дописать "Введите Завершить, чтобы закончить ввод", иначе пользователь не поймёт, что следует ввести для выхода

finalPrice = totalPrice / howPeople;
if ((int) finalPrice % 100 >= 11 && (int) finalPrice % 100 <= 14) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Можно код для определения окончания слова рубль вынести в отдельную функцию, тогда её можно будет использовать ещё и при выводе Итоговой цены в рублях, и даже стоимости товара

rubli = (int) finalPrice % 100;

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, чтобы в нем не производить дважды (int) finalPrice % 100

switch (rubli) {
case 11:
case 13:
case 12:
case 14:
rublWord = "рублей";

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 выше мы уже определяем окончание только для чисел 11-14, switch и даже переменную rubli можно убрать, оставив только строчку rublWord = "рублей";

break;
}
} else {
rubli = (int) finalPrice % 10;
switch (rubli) {
case 1:
rublWord = "рубль";
break;
case 2:
case 4:
case 3:
rublWord = "рубля";
break;
case 5:
case 6:
case 7:
case 8:
case 9:
case 0:

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Cлучаи с 5 до 0 можно объединить, написав просто default

rublWord = "рублей";
break;
}
}
productName = scanWords.next();
System.out.println("Введите стоимость продукта");
}
}
System.out.println("Добавленные товары: " + totalList + "\nИтоговая цена в рублях: " + totalPrice);
System.out.println("Каждый человек должен заплатить: "+String.format("%.2f",finalPrice)+" "+rublWord); }

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Молодец, что не дублируешь этот код, оставив в switch только определение окончания слово рубль, это хорошее решение

}
22 changes: 0 additions & 22 deletions src/main/java/Calculator.java

This file was deleted.

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.

66 changes: 24 additions & 42 deletions src/main/java/Main.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,47 +3,29 @@
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("Неверное количество друзей. Значение должно быть болье единицы, давайте попробуем еще раз.");
}
int howManyPeople = 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.

Значение 1 не используется, можно его здесь не инициализировать

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Можно отформатировать код, в студии в выбранном файле сверху вкладка Code - Reformat Code, либо Ctrl+Alt+L, тогда автоматически код выправится, проставятся правильные отступы

Scanner scanner = new Scanner(System.in);
if (scanner.hasNextInt() == false) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Можно писать вместо scanner.hasNextInt() == false просто !scanner.hasNextInt()

howManyPeople = -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.

В твоей реализации можно эту строчку убрать, поскольку проверка howManyPeople < 1 будет выполнена только в случае scanner.hasNextInt() == false

System.out.println("Введите число");
}
else {
howManyPeople = scanner.nextInt();
{

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 (howManyPeople > 1) {
break;
}
if (howManyPeople < 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));
calculator.calculate(howManyPeople);
}
}
}