Skip to content
Open
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"
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.

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

import java.util.ArrayList;
public class Main {

static ArrayList<String> goodsArray = new ArrayList<>(); //Массив товаров
static ArrayList<Double> pricesArray = new ArrayList<>(); //Массив цен

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Можно сделать дополнительный класс Product с полем name и price, и место 2 массивов держать 1 массив продуктов

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.

Да, вы правы! В первой версии были переменные и даже массив с классом goodClass, в которых записывались пары название+цена, но в процессе отладки с досадой отступил от этой красоты, и переделал на более топорный вариант(((
Как потом выяснилось, всего лишь из-за необходимости очищать сканер и из-за недопустимости сравнения дабл-сканера >0, т.к. в дабл попадали текстовые данные из названия... До конца так и не понял механику работы сканеров, но проблему обошёл по-другому...
Спасибо!

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 qtyOfGuys, qtyOfGoods;
int i = 0;
double sum = 0;
qtyOfGuys = howManyGuys.howManyGuys();
qtyOfGoods = goodsEntering.goodsArrayCreating();

System.out.println("\nДОБАВЛЕННЫЕ ТОВАРЫ: ");
while (i < qtyOfGoods){

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Можно вместо qtyOfGoods использовать goodsArray.size(). Это ещё и предотвратит от попытки получить элемент по индексу, который больше размера массива

System.out.println((i+1) + ") " + goodsArray.get(i));
sum += pricesArray.get(i);
i++;
}
}

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));
double payment = (double) sum / qtyOfGuys;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Приведение типа к double (код (double) перед sum) необязательно, потому что sum и так типа double

System.out.println("С каждого участника по " + String.format("%.2f", payment) + rubWord.rubWord(payment));
}

}

34 changes: 34 additions & 0 deletions src/main/java/goodsEntering.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import java.util.Scanner;
public class goodsEntering {
public static int goodsArrayCreating(){

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Можно метод делать не статическим, тогда для его вызова надо создавать экземпляр класса goodsEntering, и вызывать метод от экземпляра

int qtyOfGoods= 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.

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

String enteredName = "";
Double enteredPrice = 0d;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Double с большой буквы это класс-обертка, а здесь достаточно использовать примитив double. Подробнее про классы-обертки будет в спринте 3, тема 1, урок 2 Списки. ArrayList
Инициализация 0d здесь необязательно, поскольку до использования переменной её значение будет перезаписано enteredPrice = price.nextDouble();

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.

Очень долго промучился с проверками и типами данных(( В результате душевной травмы пробовал принудительно присваивать типы некоторым значениям переменных))
Стало большим сюрпризом, что нужно очищать буфер сканера, иначе случался вылет в ошибку...

Scanner name = new Scanner(System.in);
Scanner price = new Scanner(System.in);
while (!enteredName.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.

Можно сделать цикл бесконечным while(true), а при проверках ввода ставить break; для выхода из него

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.

Сэкономил строчки кода на проверках и break)) Спасибо, что обратили внимание 👍

System.out.print("\nВведите название товара №" + (qtyOfGoods+1) + ": ");
enteredName = name.nextLine();
if (!enteredName.equalsIgnoreCase("Завершить")) {
System.out.print("Введите цену товара: ");
if (price.hasNextDouble()) {
enteredPrice = price.nextDouble();
if (enteredPrice > 0) {
qtyOfGoods++;
Main.goodsArray.add(enteredName);
Main.pricesArray.add(enteredPrice);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Если убрать в Main использование qtyOfGoods и сделать один массив, то можно в этом методе goodsArrayCreating() возвращать не инт, а массив товаров, эти две строчки тогда буду не нужны, а в Main можно будет использовать результат метода

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.

Да, спасибо, пробовал так сделать! Если бы не борьба со сканерами, то так бы и было))

if (!enteredName.equalsIgnoreCase("Завершить")) {
System.out.println("Добавлен товар №" + qtyOfGoods + " '" + enteredName + "' " + "за " + String.format("%.2f", enteredPrice) + rubWord.rubWord(enteredPrice));
}
} else {
System.out.println("Цена должна быть >0! Повторите ввод...");
}
} else {
System.out.println("Это не похоже на цену! Повторите ввод...");
price.next();
}
}
} // stopWhile
return qtyOfGoods; }

}
25 changes: 25 additions & 0 deletions src/main/java/howManyGuys.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import java.util.Scanner;
public class howManyGuys {
Comment thread
sred75 marked this conversation as resolved.
static int qtyOfGuys;
public static void main(String[] args) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Этот метод здесь лучше убрать, потому что точка входа в приложение в методе main класса Main


qtyOfGuys = howManyGuys(); //проверяем и определяем кол-во человек
}
public static int howManyGuys() {
boolean flag = false;
System.out.print("На какое кол-во человек разделить счёт? ");
while (!flag) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Достаточно здесь написать в скобках true, и необходимости в переменной flag не будет

Scanner userInput = new Scanner(System.in);
if (userInput.hasNextInt()) {
qtyOfGuys = userInput.nextInt();
if (qtyOfGuys > 1) {
flag = true;
break;
} else {
System.out.println("Кол-во человек должно быть больше 1, повторите ввод:"); }
} else {
System.out.println("Некорректный ввод, укажите кол-во человек >1:"); }
}
return qtyOfGuys;
}
}
18 changes: 18 additions & 0 deletions src/main/java/rubWord.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
public class rubWord {

public static String rubWord(double payInput) {
String payOutput;
int payInputNorm = (int) payInput;
String payString = Integer.toString(payInputNorm);
char endOfPayment = payString.charAt(payString.length() - 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.

Можно более простые варианты: для определения последней цифры - payInputNorm % 10. Плюс учесть, что для чисел 11-19 окончание слова - "рублей", поможет payInputNorm % 100

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.

Классный подход, спасибо 👍)

switch (Character.toString(endOfPayment)) {
case "1": payOutput = " рубль."; break;
case "2":
case "3":
case "4":
payOutput = " рубля."; break;
default: payOutput = " рублей."; break;
}
return payOutput;
}
}