Skip to content

Андрей Трофимов консольное приложение №1 - #1

Open
A2T-user wants to merge 4 commits into
mainfrom
dev
Open

A2T-user wants to merge 4 commits into
mainfrom
dev

Conversation

@A2T-user

Copy link
Copy Markdown
Owner

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

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

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.

Спасибо

Comment thread src/main/java/LineOfBill.java Outdated
// Класс для хранения данных строки счета
public class LineOfBill {
private String name;
private float prise;

Copy link
Copy Markdown

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
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

Исправил

Comment thread src/main/java/LineOfBill.java Outdated
@@ -0,0 +1,15 @@

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

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. Это пригодится при масштабировании, если нам понадобится использовать данные не только для счета, но и для учета проданных товаров/блюд, к примеру

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.

Согласен

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

Copy link
Copy Markdown

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
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

Согласен

Comment thread src/main/java/DataInput.java Outdated
listOfProducts.add(lb); // и добавление его в массив
System.out.println("Товар успешно добавлен.");
System.out.println("Хотите добавить еще один товар?\nДля завершения процесса добавления товаров введите \"Завершить\":");
} while (!scanner.next().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.

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

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.

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

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

Copy link
Copy Markdown

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
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

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

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

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.

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

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

Copy link
Copy Markdown

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
Copy Markdown
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
Copy Markdown
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.

2 participants