-
Notifications
You must be signed in to change notification settings - Fork 0
Написал программу, написаны основной класс и методы #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
src/main/java/Main.java
Outdated
| /* | ||
| Возвращает строку, описываюющую правильное окончание в слове "рубль" в зависимости от целочисленной части. | ||
| */ | ||
| public static String getTextRub(double total, int amount) { |
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.
Лучше передать в функцию конкретное число, для которого нужно сформировать корректное окончание, а не total и amount. Таким образом, функция станет универсальнее и её будет удобнее тестировать
src/main/java/Main.java
Outdated
| */ | ||
| public static String getTextRub(double total, int amount) { | ||
| String textRub; | ||
| int rubles = (int) total / amount; |
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.
Здесь потенциально может быть деление на 0, перед делением всегда нужно проверять второй аргумент
src/main/java/Main.java
Outdated
| */ | ||
| public static void main(String[] args) { | ||
| System.out.println("Hello world!"); | ||
| byte amount = getValidAmount(); |
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.
А почему именно byte, а не int? По требованиям нет верхнего ограничения, а ты сделал его - 127 человек, так лучше не делать
src/main/java/Main.java
Outdated
| byte amount; | ||
|
|
||
| while (true) { | ||
| Scanner s = new Scanner(System.in); |
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.
Я это сделал для обхода enter для nextLine, иначе получается, что мне нужно считывать enter перед вводом названия товара второй и последующие разы.
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.
В методе getValidAmount я могу вывести scanner за пределы цикла, но в методе addProducts я не могу этого сделать, потому что я считываю название товара через nextLine, потом считываю хочет ли пользователь продолжить добавлять товары, и после того как пользователь вводит любой символ и нажимает enter, этот самый enter (\n) передается для сканнера nextLine и он его считывает как название товара, после чего сразу запрашивается стоимость товара, чтобы этого избежать, пришлось написать так, я не нашел другого способа как этого можно избежать в scanner
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/Main.java
Outdated
| /* | ||
| Предоставляет информацию о товаре. | ||
| */ | ||
| public static class Calculate { |
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
src/main/java/Main.java
Outdated
| double price; | ||
| String productName; |
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/Main.java
Outdated
| Calculate product = new Calculate(productName, price); | ||
| products.append(productName).append("\n"); | ||
| total += product.getPrice(); | ||
| System.out.println("Товар успешно добавлен.\nХотите добавить ещё один товар?"); |
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 3. добавил описание для пользователя чтобы завершить программу 4. изменил тип данных с byte на int для переменной amount по кол-ву людей для разделения счета 5. добавил условие для вывода окончания в слове рубль 6. изменил входные данные в методе getTextRub
…классе Product 3. добавил описание для пользователя чтобы завершить программу 4. изменил тип данных с byte на int для переменной amount по кол-ву людей для разделения счета 5. добавил условие для вывода окончания в слове рубль 6. изменил входные данные в методе getTextRub