Repository navigation
Реквест по заданию в спринте 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?
Changes from all commits
e1f6893
c521234
b68aa71
82a8dd3
a54fd55
ec91d41
e5858d6
d50cf48
b5d629f
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
This file was deleted.
This file was deleted.
This file was deleted.
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,49 +1,23 @@ | ||
| import java.util.Scanner; | ||
|
|
||
| import java.util.ArrayList; | ||
| public class Main { | ||
|
|
||
| static ArrayList<String> goodsArray = new ArrayList<>(); //Массив товаров | ||
| static ArrayList<Double> pricesArray = new ArrayList<>(); //Массив цен | ||
| public static void main(String[] args) { | ||
| Scanner scanner = new Scanner(System.in); | ||
|
|
||
| int friendCount; | ||
| while (true) { | ||
| System.out.println("На сколько человек необходимо разделить счет?"); | ||
| friendCount = scanner.nextInt(); | ||
|
|
||
| if (friendCount > 1) { | ||
| break; | ||
| } else if (friendCount == 1) { | ||
| System.out.println( | ||
| "Нет смысла делить сумму на одного человека. Давайте попробуем ввести другое значение, которое будет больше единицы."); | ||
| } else { | ||
| System.out.println("Неверное количество друзей. Значение должно быть болье единицы, давайте попробуем еще раз."); | ||
| int qtyOfGuys, qtyOfGoods; | ||
| int i = 0; | ||
| double sum = 0; | ||
| qtyOfGuys = howManyGuys.howManyGuys(); | ||
| qtyOfGoods = goodsEntering.goodsArrayCreating(); | ||
|
|
||
| System.out.println("\nДОБАВЛЕННЫЕ ТОВАРЫ: "); | ||
| while (i < qtyOfGoods){ | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Можно вместо qtyOfGoods использовать goodsArray.size(). Это ещё и предотвратит от попытки получить элемент по индексу, который больше размера массива |
||
| System.out.println((i+1) + ") " + goodsArray.get(i)); | ||
| sum += pricesArray.get(i); | ||
| i++; | ||
| } | ||
| } | ||
|
|
||
| Calculator calculator = new Calculator(friendCount); | ||
|
|
||
| while (true) { | ||
| System.out.println("Введите название товара"); | ||
| String name = scanner.next(); | ||
|
|
||
| System.out.println("Введите стоимость товара в формате: 'рубли.копейки' [10.45, 11.40]"); | ||
| double price = scanner.nextDouble(); | ||
|
|
||
| calculator.addItem(new Item(name, price)); | ||
|
|
||
| System.out.println( | ||
| "Хотите добавить еще один товар? Введите любой символ для продолжения, либо 'Завершить' если больше нет товаров для добавления"); | ||
| String answer = scanner.next(); | ||
|
|
||
| if (answer.equalsIgnoreCase("Завершить")) { | ||
| break; | ||
| } | ||
| } | ||
|
|
||
| double result = calculator.divideSum(); | ||
| Formatter formatter = new Formatter(); | ||
|
|
||
| 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 commentThe reason will be displayed to describe this comment to others. Learn more. Приведение типа к double (код |
||
| System.out.println("С каждого участника по " + String.format("%.2f", payment) + rubWord.rubWord(payment)); | ||
| } | ||
|
|
||
| } | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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 commentThe reason will be displayed to describe this comment to others. Learn more. Можно метод делать не статическим, тогда для его вызова надо создавать экземпляр класса goodsEntering, и вызывать метод от экземпляра |
||
| int qtyOfGoods= 0; | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Можешь применить в студии автоформатирование (в выбранном файле, сверху вкладка Code - Reformat Code, либо Ctrl+Alt+L), тогда автоматически код выправится. |
||
| String enteredName = ""; | ||
| Double enteredPrice = 0d; | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Double с большой буквы это класс-обертка, а здесь достаточно использовать примитив
Owner
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Очень долго промучился с проверками и типами данных(( В результате душевной травмы пробовал принудительно присваивать типы некоторым значениям переменных)) |
||
| 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 commentThe reason will be displayed to describe this comment to others. Learn more. Можно сделать цикл бесконечным
Owner
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Сэкономил строчки кода на проверках и break)) Спасибо, что обратили внимание 👍 |
||
| System.out.print("\nВведите название товара №" + (qtyOfGoods+1) + ": "); | ||
| enteredName = name.nextLine(); | ||
| if (!enteredName.equalsIgnoreCase("Завершить")) { | ||
| System.out.print("Введите цену товара: "); | ||
| if (price.hasNextDouble()) { | ||
| enteredPrice = price.nextDouble(); | ||
| if (enteredPrice > 0) { | ||
| qtyOfGoods++; | ||
| Main.goodsArray.add(enteredName); | ||
| Main.pricesArray.add(enteredPrice); | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Если убрать в Main использование qtyOfGoods и сделать один массив, то можно в этом методе goodsArrayCreating() возвращать не инт, а массив товаров, эти две строчки тогда буду не нужны, а в Main можно будет использовать результат метода
Owner
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Да, спасибо, пробовал так сделать! Если бы не борьба со сканерами, то так бы и было)) |
||
| if (!enteredName.equalsIgnoreCase("Завершить")) { | ||
| System.out.println("Добавлен товар №" + qtyOfGoods + " '" + enteredName + "' " + "за " + String.format("%.2f", enteredPrice) + rubWord.rubWord(enteredPrice)); | ||
| } | ||
| } else { | ||
| System.out.println("Цена должна быть >0! Повторите ввод..."); | ||
| } | ||
| } else { | ||
| System.out.println("Это не похоже на цену! Повторите ввод..."); | ||
| price.next(); | ||
| } | ||
| } | ||
| } // stopWhile | ||
| return qtyOfGoods; } | ||
|
|
||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,25 @@ | ||
| import java.util.Scanner; | ||
| public class howManyGuys { | ||
|
sred75 marked this conversation as resolved.
|
||
| static int qtyOfGuys; | ||
| public static void main(String[] args) { | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Этот метод здесь лучше убрать, потому что точка входа в приложение в методе main класса Main |
||
|
|
||
| qtyOfGuys = howManyGuys(); //проверяем и определяем кол-во человек | ||
| } | ||
| 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 commentThe reason will be displayed to describe this comment to others. Learn more. Достаточно здесь написать в скобках true, и необходимости в переменной flag не будет |
||
| Scanner userInput = new Scanner(System.in); | ||
| if (userInput.hasNextInt()) { | ||
| qtyOfGuys = userInput.nextInt(); | ||
| if (qtyOfGuys > 1) { | ||
| flag = true; | ||
| break; | ||
| } else { | ||
| System.out.println("Кол-во человек должно быть больше 1, повторите ввод:"); } | ||
| } else { | ||
| System.out.println("Некорректный ввод, укажите кол-во человек >1:"); } | ||
| } | ||
| return qtyOfGuys; | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,18 @@ | ||
| public class rubWord { | ||
|
|
||
| public static String rubWord(double payInput) { | ||
| 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 commentThe reason will be displayed to describe this comment to others. Learn more. Можно более простые варианты: для определения последней цифры - payInputNorm % 10. Плюс учесть, что для чисел 11-19 окончание слова - "рублей", поможет payInputNorm % 100
Owner
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Классный подход, спасибо 👍) |
||
| switch (Character.toString(endOfPayment)) { | ||
| case "1": payOutput = " рубль."; break; | ||
| case "2": | ||
| case "3": | ||
| case "4": | ||
| payOutput = " рубля."; break; | ||
| default: payOutput = " рублей."; break; | ||
| } | ||
| return payOutput; | ||
| } | ||
| } | ||
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 с полем name и price, и место 2 массивов держать 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.
Да, вы правы! В первой версии были переменные и даже массив с классом goodClass, в которых записывались пары название+цена, но в процессе отладки с досадой отступил от этой красоты, и переделал на более топорный вариант(((
Как потом выяснилось, всего лишь из-за необходимости очищать сканер и из-за недопустимости сравнения дабл-сканера >0, т.к. в дабл попадали текстовые данные из названия... До конца так и не понял механику работы сканеров, но проблему обошёл по-другому...
Спасибо!