-
Notifications
You must be signed in to change notification settings - Fork 0
Dev4 #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?
Dev4 #2
Changes from all commits
de19ed0
cb01464
55b8920
c9bad5c
9fb1813
050146f
c613765
e54fcf2
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,2 +1,66 @@ | ||
| package PACKAGE_NAME;public class AccountDivider { | ||
| import java.util.InputMismatchException; | ||
| import java.util.Scanner; | ||
|
|
||
| public class AccountDivider { | ||
| public void start() { | ||
| Scanner scanner = new Scanner(System.in); | ||
|
|
||
| // Запрашиваю кол-во гостей | ||
| int kGuests; | ||
| while (true) { | ||
| try { | ||
| System.out.print("Введите количество гостей: "); | ||
| kGuests = scanner.nextInt(); | ||
| if (kGuests < 1) { | ||
| System.out.println("Некорректное количество гостей. Гостей не может быть 0."); | ||
| } else { | ||
| break; | ||
| } | ||
| } catch (InputMismatchException e) { | ||
| System.out.println("Некорректный ввод. Введите целое положительное число."); | ||
| scanner.nextLine(); // Очистка буфера | ||
| } | ||
| } | ||
|
|
||
|
|
||
| // Добавление товаров | ||
| Calculator calculator = new Calculator(); | ||
| int itemsCount = calculator.getItems().size(); | ||
| while (true) { | ||
| System.out.print("Введите название товара или 'Завершить', чтобы закончить: "); | ||
| String productName = scanner.next(); | ||
| if (productName.equalsIgnoreCase("завершить")) { | ||
| break; | ||
| } | ||
| System.out.print("Введите стоимость товара: "); | ||
| double productPrice; | ||
| while (true) { | ||
| try { | ||
| productPrice = Double.parseDouble(scanner.next()); | ||
| if (productPrice <= 0) { | ||
| throw new NumberFormatException(); | ||
| } | ||
| break; | ||
| } catch (NumberFormatException e) { | ||
| System.out.println("Ошибка: стоимость товара должна быть положительным числом. Повторите ввод."); | ||
| } | ||
| } | ||
| calculator.addItem(productName, productPrice); | ||
| if (calculator.getItems().size() > itemsCount) { | ||
| System.out.println("Товар успешно добавлен."); | ||
| itemsCount++; | ||
| } | ||
| } | ||
|
|
||
|
|
||
|
|
||
|
|
||
| // Вывод результатов | ||
| System.out.println("Добавленные товары:"); | ||
| for (Calculator.Item item : calculator.getItems()) { | ||
| System.out.println(item.getName() + ": " + String.format("%.2f", item.getPrice()) + " руб."); | ||
| } | ||
|
|
||
| calculator.splitBill(kGuests); | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,9 +1,10 @@ | ||
| import java.util.ArrayList; | ||
| import java.util.List; | ||
| import java.util.Scanner; | ||
|
|
||
|
|
||
| public class Calculator { | ||
|
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. Разделение счета: В методе splitBill(int kGuests) класса Calculator есть ошибка при определении окончания для слова "рубль". У тебя есть проверка part % 10 == 1 && part % 100 != 11, которая верна только для чисел, заканчивающихся на 1, кроме чисел, оканчивающихся на 11. Однако, это не учитывает случаи чисел, заканчивающихся на 11, 12 и 13, которые также используют слово "рублей", а не "рубль". 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. Метод splitBill(int kGuests) класса Calculator имеет некоторые повторяющиеся участки кода, такие как форматирование вывода суммы и окончания. Ты можешь вынести этот код в отдельный метод для повышения читаемости и поддерживаемости кода |
||
| private List<Item> items; | ||
|
|
||
| List<Item> items; | ||
|
|
||
| public Calculator() { | ||
| this.items = new ArrayList<>(); | ||
|
|
@@ -21,7 +22,7 @@ public double getTotalBill() { | |
| return total; | ||
| } | ||
|
|
||
| public List<Item> getItems() { | ||
| List<Item> getItems() { | ||
| return items; | ||
| } | ||
|
|
||
|
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. В методе addItem(String name, double price) класса Calculator нет проверки на пустое имя товара или неположительную цену. Можно добавить проверки на такие случаи и предпринять соответствующие действия (например, вывести сообщение об ошибке и запросить ввод данных еще раз). |
||
|
|
@@ -37,22 +38,24 @@ public void splitBill(int kGuests) { | |
| // Определение окончания для "рубль" | ||
| String suffix; | ||
| int part = (int) totalBill; | ||
| if (part % 10 == 1 &&part % 100 != 11) { | ||
| int finalNumbers = part % 100; | ||
| if (part % 10 == 1 && finalNumbers != 11) { | ||
| suffix = "рубль"; | ||
| } else if (part % 10 >= 2 &&part % 10 <= 4 && (part % 100 < 10 ||part % 100 >= 20)) { | ||
| } else if (part % 10 >= 2 && part % 10 <= 4 && !(finalNumbers >= 12 && finalNumbers <= 14)) { | ||
| suffix = "рубля"; | ||
| } else { | ||
| suffix = "рублей"; | ||
| } | ||
|
|
||
|
|
||
| System.out.println("Общая сумма счета: " + String.format("%.2f", totalBill) + " " + suffix + "."); | ||
| System.out.println("Каждый гость должен заплатить по: " + String.format("%.2f", perPerson) + " " + suffix + "."); | ||
| } | ||
|
|
||
|
|
||
| static class Item { | ||
| private String name; | ||
| private double price; | ||
| String name; | ||
| double price; | ||
|
|
||
| public Item(String name, double price) { | ||
| this.name = name; | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,6 +1,8 @@ | ||
|
|
||
| public class Main { | ||
| public static void main(String[] args) { | ||
| System.out.println("Hello world!"); | ||
| AccountDivider AccountDivider = new AccountDivider(); | ||
| AccountDivider.start(); | ||
|
|
||
| } | ||
| } | ||
| } |
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.
В методе start класса AccountDivider необходимо предусмотреть обработку исключений, которые могут возникнуть при вводе пользователя. Например, если пользователь введет не числовое значение при запросе количества гостей или стоимости товара, программа может завершиться с ошибкой InputMismatchException.