Repository navigation
Яндекс практикум, консольное приложение № 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?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,22 +1,57 @@ | ||
| class Calculator { | ||
| import java.util.ArrayList; | ||
|
|
||
| int friendsCount; | ||
| public class Calculator { | ||
|
|
||
| String cart = "Добавленные товары:"; | ||
| double totalPrice = 0; | ||
| public static int peopleCount; | ||
| private static final ArrayList<Good> basket = new ArrayList<>(); | ||
|
|
||
| Calculator(int friendsCount) { | ||
| this.friendsCount = friendsCount; | ||
| public static void addNewGood(Good good) { | ||
| basket.add(good); | ||
| System.out.printf("Добавлен новый товар [" + good.goodLabel + "] стоимостью [%.2f] " | ||
| + setRoubleCase(good.goodPrice) + "\n", good.goodPrice); | ||
| } | ||
|
|
||
| void addItem(Item item) { | ||
| totalPrice += item.price; | ||
| cart = cart + "\n" + item.name; | ||
| public static void printCheck() { | ||
| printGoods(); | ||
| double totalPrice = getTotalPrice(); | ||
| System.out.printf("Общая сумма: %.2f %s%n", totalPrice, setRoubleCase(totalPrice)); | ||
| System.out.printf("Количество человек: %s%n", peopleCount); | ||
| double shareRatio = getShareRatio(totalPrice, peopleCount); | ||
| System.out.printf("Каждый должен заплатить: %.2f %s%n", shareRatio, setRoubleCase(shareRatio)); | ||
| } | ||
|
|
||
| public static void printGoods() { | ||
| System.out.print("Добавленные товары:\n"); | ||
| for (int i = 0; i < basket.size(); i++) { | ||
| System.out.printf("Товар [" + basket.get(i).goodLabel + "] стоимостью [%.2f] " | ||
| + setRoubleCase(basket.get(i).goodPrice) + "\n", basket.get(i).goodPrice); | ||
| } | ||
| } | ||
|
|
||
| System.out.println(item.name + " в корзине"); | ||
| public static double getTotalPrice() { | ||
| double totalPrice = 0; | ||
| for (int i = 0; i < basket.size(); i++) { | ||
| totalPrice = totalPrice + basket.get(i).goodPrice; | ||
| } | ||
| return totalPrice; | ||
| } | ||
|
|
||
| double divideSum() { | ||
| return totalPrice / friendsCount; | ||
| public static double getShareRatio(double totalPrice, double peopleCount) { | ||
| return totalPrice / peopleCount; | ||
| } | ||
|
|
||
| private static String setRoubleCase(double d) { | ||
|
|
||
| int n1 = (int) d % 100; | ||
| int n2 = n1 % 10; | ||
|
|
||
| if (n1 > 10 && n1 < 20) { | ||
| return "рублей"; | ||
| }else if (n2 > 1 && n2 < 5) { | ||
| return "рубля"; | ||
| }else if (n2 == 1) { | ||
| return "рубль"; | ||
| }else | ||
| return "рублей"; | ||
| } | ||
| } | ||
| } | ||
This file was deleted.
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,11 @@ | ||
| public class Good { | ||
|
|
||
| String goodLabel; | ||
| Double goodPrice; | ||
|
|
||
| Good(String goodLabel, Double goodPrice) { | ||
| this.goodLabel = goodLabel; | ||
| this.goodPrice = goodPrice; | ||
| } | ||
|
|
||
| } |
This file was deleted.
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,49 +1,84 @@ | ||
| import java.util.Scanner; | ||
|
|
||
|
|
||
| public class Main { | ||
|
|
||
| static Scanner scanner = new Scanner(System.in); | ||
|
|
||
| public static void main(String[] args) { | ||
| Scanner scanner = new Scanner(System.in); | ||
| System.out.print("Добро пожаловать в систему совместных закупок!\n"); | ||
| getPeopleCount(); | ||
| getGoods(); | ||
| Calculator.printCheck(); | ||
| } | ||
|
|
||
| int friendCount; | ||
| while (true) { | ||
| System.out.println("На сколько человек необходимо разделить счет?"); | ||
| friendCount = scanner.nextInt(); | ||
| static void getPeopleCount() { | ||
| int peopleCount; | ||
|
|
||
| if (friendCount > 1) { | ||
| break; | ||
| } else if (friendCount == 1) { | ||
| System.out.println( | ||
| "Нет смысла делить сумму на одного человека. Давайте попробуем ввести другое значение, которое будет больше единицы."); | ||
| System.out.print("Сколько человек будет приобретать товары?\n"); | ||
|
|
||
| while (true) { | ||
| if (scanner.hasNextInt()) { | ||
| int input = scanner.nextInt(); | ||
| if (input >= 2) { | ||
| peopleCount = input; | ||
| break; | ||
| } else { | ||
| System.out.print("Ошибка: неверный ввод!\n"); | ||
| } | ||
|
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. Можно убрать этот блок с else, выводить сообщение "Ошибка: неверный ввод!" в конце while вне всех if-else - так можно сократить и оптимизировать этот блок |
||
| } else { | ||
| System.out.println("Неверное количество друзей. Значение должно быть болье единицы, давайте попробуем еще раз."); | ||
| System.out.print("Ошибка: неверный ввод!\n"); | ||
| scanner.next(); | ||
| } | ||
| } | ||
| Calculator.peopleCount = peopleCount; | ||
| } | ||
|
|
||
| static void getGoods() { | ||
|
|
||
| Calculator calculator = new Calculator(friendCount); | ||
| String goodLabel; | ||
| double goodPrice; | ||
|
|
||
| System.out.print("Введите название товара:\n"); | ||
| goodLabel = scanner.next(); | ||
|
|
||
| while (true) { | ||
| System.out.println("Введите название товара"); | ||
| String name = scanner.next(); | ||
|
|
||
| System.out.println("Введите стоимость товара в формате: 'рубли.копейки' [10.45, 11.40]"); | ||
| double price = scanner.nextDouble(); | ||
| System.out.print("Введите стоимость товара [" + goodLabel + "] в формате: \"руб.коп\", например [10.45, 11.40]:\n"); | ||
|
|
||
| while (true) { | ||
|
|
||
| if (scanner.hasNextDouble()) { | ||
| double input = scanner.nextDouble(); | ||
| if (isRightFormat(input)) { | ||
| goodPrice = input; | ||
| break; | ||
| } else { | ||
| System.out.print("Ошибка: неверный ввод!\n"); | ||
|
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. Строка "Ошибка: неверный ввод!\n" встречается несколько раз в программе, имеет смысл вынести её в отдельную переменную. Основное преимущество такого подхода - при необходимости поменять текст надо будет поменять только текст в переменной
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. Понял, благодарю! |
||
| } | ||
| } else { | ||
| System.out.print("Ошибка: неверный ввод!\n"); | ||
| scanner.next(); | ||
| } | ||
| } | ||
|
|
||
| calculator.addItem(new Item(name, price)); | ||
| Calculator.addNewGood(new Good(goodLabel, goodPrice)); | ||
|
|
||
| System.out.println( | ||
| "Хотите добавить еще один товар? Введите любой символ для продолжения, либо 'Завершить' если больше нет товаров для добавления"); | ||
| String answer = scanner.next(); | ||
| System.out.print("Введите название товара, или введите \"Завершить\", чтобы закончить:\n"); | ||
| String input = scanner.next(); | ||
|
|
||
| if (answer.equalsIgnoreCase("Завершить")) { | ||
| if (input.equalsIgnoreCase("Завершить")) { | ||
| break; | ||
| } else { | ||
| goodLabel = input; | ||
| } | ||
| } | ||
|
|
||
| double result = calculator.divideSum(); | ||
| Formatter formatter = new Formatter(); | ||
| } | ||
| } | ||
|
|
||
| System.out.println(calculator.cart); | ||
| System.out.println("Каждому человеку к оплате: " + formatter.roundResult(result) + " " + formatter.formatValue(result)); | ||
| static boolean isRightFormat (Double d) { | ||
| String[] splitter = String.valueOf(d).split("[.]"); | ||
| int l = splitter[1].length(); | ||
| return (d > 0) && (l <= 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.
Идущие подряд множественные if - else if - else можно ещё заменить конструкцией switch-case