-
Notifications
You must be signed in to change notification settings - Fork 0
Реквест по заданию в спринте 2 Практикума #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
# Conflicts: # src/main/java/goodsAddingEngine.java
…тывается некорректный ввод, прога вылетает
…le, переписал логику в новом классе goodsEntering, вылетов нет
| import java.util.Scanner; | ||
| public class goodsEntering { | ||
| public static int goodsArrayCreating(){ | ||
| int qtyOfGoods= 0; |
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.
Можешь применить в студии автоформатирование (в выбранном файле, сверху вкладка Code - Reformat Code, либо Ctrl+Alt+L), тогда автоматически код выправится.
|
|
||
| System.out.println(calculator.cart); | ||
| System.out.println("Каждому человеку к оплате: " + formatter.roundResult(result) + " " + formatter.formatValue(result)); | ||
| double payment = (double) sum / qtyOfGuys; |
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.
Приведение типа к double (код (double) перед sum) необязательно, потому что sum и так типа double
| public static int goodsArrayCreating(){ | ||
| int qtyOfGoods= 0; | ||
| String enteredName = ""; | ||
| Double enteredPrice = 0d; |
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.
Double с большой буквы это класс-обертка, а здесь достаточно использовать примитив double. Подробнее про классы-обертки будет в спринте 3, тема 1, урок 2 Списки. ArrayList
Инициализация 0d здесь необязательно, поскольку до использования переменной её значение будет перезаписано enteredPrice = price.nextDouble();
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.
Очень долго промучился с проверками и типами данных(( В результате душевной травмы пробовал принудительно присваивать типы некоторым значениям переменных))
Стало большим сюрпризом, что нужно очищать буфер сканера, иначе случался вылет в ошибку...
| Double enteredPrice = 0d; | ||
| Scanner name = new Scanner(System.in); | ||
| Scanner price = new Scanner(System.in); | ||
| while (!enteredName.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.
Можно сделать цикл бесконечным while(true), а при проверках ввода ставить break; для выхода из него
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.
Сэкономил строчки кода на проверках и break)) Спасибо, что обратили внимание 👍
| qtyOfGoods = goodsEntering.goodsArrayCreating(); | ||
|
|
||
| System.out.println("\nДОБАВЛЕННЫЕ ТОВАРЫ: "); | ||
| while (i < qtyOfGoods){ |
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.
Можно вместо qtyOfGoods использовать goodsArray.size(). Это ещё и предотвратит от попытки получить элемент по индексу, который больше размера массива
| @@ -0,0 +1,34 @@ | |||
| import java.util.Scanner; | |||
| public class goodsEntering { | |||
| public static int goodsArrayCreating(){ | |||
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.
Можно метод делать не статическим, тогда для его вызова надо создавать экземпляр класса goodsEntering, и вызывать метод от экземпляра
| import java.util.Scanner; | ||
| public class howManyGuys { | ||
| static int qtyOfGuys; | ||
| public static void main(String[] args) { |
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.
Этот метод здесь лучше убрать, потому что точка входа в приложение в методе main класса Main
| public static int howManyGuys() { | ||
| boolean flag = false; | ||
| System.out.print("На какое кол-во человек разделить счёт? "); | ||
| while (!flag) { |
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.
Достаточно здесь написать в скобках true, и необходимости в переменной flag не будет
| String payOutput; | ||
| int payInputNorm = (int) payInput; | ||
| String payString = Integer.toString(payInputNorm); | ||
| char endOfPayment = payString.charAt(payString.length() - 1); |
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.
Можно более простые варианты: для определения последней цифры - payInputNorm % 10. Плюс учесть, что для чисел 11-19 окончание слова - "рублей", поможет payInputNorm % 100
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.
Классный подход, спасибо 👍)
Рабочий коммит - 050