Skip to content

Conversation

@A2T-user
Copy link
Owner

Написал этот код, четко следуя заданию, хотя считаю что алгоритм можно улучшить

int numberOfPersons = dataInput.numberOfPeople(scanner);
// Ввод товара
ArrayList<LineOfBill> listOfProducts = dataInput.productEntry(scanner);
scanner.close(); // Закрыть сканер

Choose a reason for hiding this comment

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

👏 Круто, что не забываешь завершить работу со сканнером

Copy link
Owner Author

Choose a reason for hiding this comment

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

Спасибо

// Класс для хранения данных строки счета
public class LineOfBill {
private String name;
private float prise;

Choose a reason for hiding this comment

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

🍏 Закралась опечатка)

Suggested change
private float prise;
private float price;

Copy link
Owner Author

Choose a reason for hiding this comment

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

Исправил

@@ -0,0 +1,15 @@

// Класс для хранения данных строки счета
public class LineOfBill {

Choose a reason for hiding this comment

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

🍏 Рекомендую назвать класс, например, Product. Это пригодится при масштабировании, если нам понадобится использовать данные не только для счета, но и для учета проданных товаров/блюд, к примеру

Copy link
Owner Author

Choose a reason for hiding this comment

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

Согласен

// Ввод кол-ва человек
public int numberOfPeople (Scanner scanner) {
int col;
String s = "\nВведите целое число больше 1.", s1 = "На сколько человек необходимо разделить счёт:";

Choose a reason for hiding this comment

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

🍏 Рекомендую давать переменным более развернутые названия, чтобы в любой строке кода легко было понять, с чем мы работаем.
Также в java принято каждую переменную писать в отдельной строке, так их проще читать:
https://www.oracle.com/java/technologies/javase/codeconventions-declarations.html

Неизменяемые поля можно сразу объявить константами, тогда они будут созданы один раз во время компиляции:
https://www.baeldung.com/java-constants-good-practices

Copy link
Owner Author

Choose a reason for hiding this comment

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

Согласен

listOfProducts.add(lb); // и добавление его в массив
System.out.println("Товар успешно добавлен.");
System.out.println("Хотите добавить еще один товар?\nДля завершения процесса добавления товаров введите \"Завершить\":");
} while (!scanner.next().equalsIgnoreCase("Завершить"));

Choose a reason for hiding this comment

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

🍏 Можно вынести слово "Завершить" в константу. Тогда если в будущем мы захотим заменить завершающую команду на другое слово, то это нужно будет сделать в одном месте

Copy link
Owner Author

Choose a reason for hiding this comment

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

Разумно. Внесу изменения

if (col < 0) {
System.out.println("Это отрицательное число!" + s);
} else if (col == 0) {
System.out.println("На 0 делить нельзя!" + s + "\n" + s1);

Choose a reason for hiding this comment

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

🍏 При печати в памяти будут создаваться промежуточные строки из-за множественного использования оператора "+". Можно использовать StringBuilder, который сформирует только результирующую строку, System.out.printf или String.format().
https://habr.com/ru/articles/260767/

Copy link
Owner Author

Choose a reason for hiding this comment

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

Согласен. Внесу изменения

}
// Проверка - у цены должно быть две цифры после десятичной точки
String[] strPrice = String.valueOf(price).split("\\.", 2); // Разбиваем строку на массив из 2-х строк: целая часть и дробная
if (strPrice[1].length() > 2) { // Если в дробной части больше 2 знаков

Choose a reason for hiding this comment

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

🍏 число 2 можно вынести в константу и дать ему имя, чтобы всегда было понятно, почему у него именно такая величина

Copy link
Owner Author

Choose a reason for hiding this comment

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

Не совсем понял о какой 2 идет речь.
В split 2 означает, что строка будет разбита на два массива. Там всегда будет двойка.
А в if без проблем поменяю

}
System.out.println(String.format("---------------------" + "Итого по счету: %.2f\n", sumBill)); // Подчеркивание и вывод итоговой суммы по счету
double fromEveryPerson = sumBill / numberOfPersons;
System.out.println(String.format("\nГоспода, с Вас по: %.2f " + rubles(fromEveryPerson) + "%n", fromEveryPerson)); // Вывод доли счета

Choose a reason for hiding this comment

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

Еще можно вот так:

Suggested change
System.out.println(String.format("\nГоспода, с Вас по: %.2f " + rubles(fromEveryPerson) + "%n", fromEveryPerson)); // Вывод доли счета
System.out.printf("\nГоспода, с Вас по: %.2f %s%n", fromEveryPerson, rubles(fromEveryPerson));

Copy link
Owner Author

Choose a reason for hiding this comment

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

Я знаю, просто так нас учили. Исправлю

@A2T-user
Copy link
Owner Author

Спасибо за замечания. Внес все изменения. Отправляю на проверку

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants