Repository navigation
Калькулятор меню 2.0, по правкам #2
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
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.
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,65 @@ | ||
| import java.util.Scanner; | ||
|
|
||
| public class Calculate { | ||
| float price; | ||
| int rubli; | ||
| String rublWord; | ||
| String productName = ""; | ||
| float totalPrice; | ||
| String totalList = ""; | ||
| String stopWord = "Завершить"; | ||
| Scanner scanWords = new Scanner(System.in); | ||
| float finalPrice; | ||
|
|
||
| public void calculate(int howPeople) { | ||
| System.out.println("Какой товар Вы хотите добавить?"); | ||
| productName = scanWords.next(); | ||
| System.out.println("Введите стоимость продукта"); | ||
| while (!productName.equalsIgnoreCase(stopWord)) { | ||
| Scanner scanPrice = new Scanner(System.in); | ||
| if (scanPrice.hasNextFloat() == false) { | ||
| System.out.println("Вы ввели неверную стоимость товара. Введите стоимость в виде цифр"); | ||
| } else { | ||
| totalList = totalList + "\n" + productName; | ||
| price = scanPrice.nextFloat(); | ||
| totalPrice = totalPrice + price; | ||
| System.out.println("Вы успешно добавили товар " + productName + " стоимостью: " + price + ". Вы хотите добавить что-то ещё?"); | ||
| finalPrice = totalPrice / howPeople; | ||
| if ((int) finalPrice % 100 >= 11 && (int) finalPrice % 100 <= 14) { | ||
|
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. Можно код для определения окончания слова рубль вынести в отдельную функцию, тогда её можно будет использовать ещё и при выводе Итоговой цены в рублях, и даже стоимости товара |
||
| rubli = (int) finalPrice % 100; | ||
|
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, чтобы в нем не производить дважды |
||
| switch (rubli) { | ||
| case 11: | ||
| case 13: | ||
| case 12: | ||
| case 14: | ||
| rublWord = "рублей"; | ||
|
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 выше мы уже определяем окончание только для чисел 11-14, switch и даже переменную rubli можно убрать, оставив только строчку |
||
| break; | ||
| } | ||
| } else { | ||
| rubli = (int) finalPrice % 10; | ||
| switch (rubli) { | ||
| case 1: | ||
| rublWord = "рубль"; | ||
| break; | ||
| case 2: | ||
| case 4: | ||
| case 3: | ||
| rublWord = "рубля"; | ||
| break; | ||
| case 5: | ||
| case 6: | ||
| case 7: | ||
| case 8: | ||
| case 9: | ||
| case 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. Cлучаи с 5 до 0 можно объединить, написав просто default |
||
| rublWord = "рублей"; | ||
| break; | ||
| } | ||
| } | ||
| productName = scanWords.next(); | ||
| System.out.println("Введите стоимость продукта"); | ||
| } | ||
| } | ||
| System.out.println("Добавленные товары: " + totalList + "\nИтоговая цена в рублях: " + totalPrice); | ||
| System.out.println("Каждый человек должен заплатить: "+String.format("%.2f",finalPrice)+" "+rublWord); } | ||
|
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 только определение окончания слово рубль, это хорошее решение |
||
| } | ||
This file was deleted.
This file was deleted.
This file was deleted.
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -3,47 +3,29 @@ | |
| public class Main { | ||
|
|
||
| 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 howManyPeople = 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. Значение 1 не используется, можно его здесь не инициализировать |
||
| Calculate calculator = new Calculate(); | ||
| System.out.println("На сколько человек необходимо разделить счет?"); | ||
| while (true) { | ||
|
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, тогда автоматически код выправится, проставятся правильные отступы |
||
| Scanner scanner = new Scanner(System.in); | ||
| if (scanner.hasNextInt() == false) { | ||
|
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. Можно писать вместо |
||
| howManyPeople = -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. В твоей реализации можно эту строчку убрать, поскольку проверка howManyPeople < 1 будет выполнена только в случае |
||
| System.out.println("Введите число"); | ||
| } | ||
| else { | ||
| howManyPeople = scanner.nextInt(); | ||
| { | ||
|
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 (howManyPeople > 1) { | ||
| break; | ||
| } | ||
| if (howManyPeople < 1) { | ||
| System.out.println("Вы ввели неверное количество человек, введите верное количество."); | ||
| } else { | ||
| System.out.println("Вы хотите поделить счет на одного человека, но зачем? Я понимаю, вы возможно одиноки, но смысла в этом нет. Введите верное количество людей."); | ||
| } | ||
| } | ||
| } | ||
| } | ||
|
|
||
| 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)); | ||
| calculator.calculate(howManyPeople); | ||
| } | ||
| } | ||
| } | ||
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.
Тут лучше дописать "Введите Завершить, чтобы закончить ввод", иначе пользователь не поймёт, что следует ввести для выхода