-
Notifications
You must be signed in to change notification settings - Fork 0
Андрей Трофимов консольное приложение №1 #1
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Conversation
| int numberOfPersons = dataInput.numberOfPeople(scanner); | ||
| // Ввод товара | ||
| ArrayList<LineOfBill> listOfProducts = dataInput.productEntry(scanner); | ||
| scanner.close(); // Закрыть сканер |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
👏 Круто, что не забываешь завершить работу со сканнером
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Спасибо
src/main/java/LineOfBill.java
Outdated
| // Класс для хранения данных строки счета | ||
| public class LineOfBill { | ||
| private String name; | ||
| private float prise; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🍏 Закралась опечатка)
| private float prise; | |
| private float price; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Исправил
src/main/java/LineOfBill.java
Outdated
| @@ -0,0 +1,15 @@ | |||
|
|
|||
| // Класс для хранения данных строки счета | |||
| public class LineOfBill { | |||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🍏 Рекомендую назвать класс, например, Product. Это пригодится при масштабировании, если нам понадобится использовать данные не только для счета, но и для учета проданных товаров/блюд, к примеру
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Согласен
src/main/java/DataInput.java
Outdated
| // Ввод кол-ва человек | ||
| public int numberOfPeople (Scanner scanner) { | ||
| int col; | ||
| String s = "\nВведите целое число больше 1.", s1 = "На сколько человек необходимо разделить счёт:"; |
There was a problem hiding this comment.
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
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Согласен
src/main/java/DataInput.java
Outdated
| listOfProducts.add(lb); // и добавление его в массив | ||
| System.out.println("Товар успешно добавлен."); | ||
| System.out.println("Хотите добавить еще один товар?\nДля завершения процесса добавления товаров введите \"Завершить\":"); | ||
| } while (!scanner.next().equalsIgnoreCase("Завершить")); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🍏 Можно вынести слово "Завершить" в константу. Тогда если в будущем мы захотим заменить завершающую команду на другое слово, то это нужно будет сделать в одном месте
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Разумно. Внесу изменения
src/main/java/DataInput.java
Outdated
| if (col < 0) { | ||
| System.out.println("Это отрицательное число!" + s); | ||
| } else if (col == 0) { | ||
| System.out.println("На 0 делить нельзя!" + s + "\n" + s1); |
There was a problem hiding this comment.
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/
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Согласен. Внесу изменения
src/main/java/DataInput.java
Outdated
| } | ||
| // Проверка - у цены должно быть две цифры после десятичной точки | ||
| String[] strPrice = String.valueOf(price).split("\\.", 2); // Разбиваем строку на массив из 2-х строк: целая часть и дробная | ||
| if (strPrice[1].length() > 2) { // Если в дробной части больше 2 знаков |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🍏 число 2 можно вынести в константу и дать ему имя, чтобы всегда было понятно, почему у него именно такая величина
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Не совсем понял о какой 2 идет речь.
В split 2 означает, что строка будет разбита на два массива. Там всегда будет двойка.
А в if без проблем поменяю
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)); // Вывод доли счета |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Еще можно вот так:
| System.out.println(String.format("\nГоспода, с Вас по: %.2f " + rubles(fromEveryPerson) + "%n", fromEveryPerson)); // Вывод доли счета | |
| System.out.printf("\nГоспода, с Вас по: %.2f %s%n", fromEveryPerson, rubles(fromEveryPerson)); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Я знаю, просто так нас учили. Исправлю
|
Спасибо за замечания. Внес все изменения. Отправляю на проверку |
Написал этот код, четко следуя заданию, хотя считаю что алгоритм можно улучшить