Repository navigation
first dedlain #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 +1 @@ | ||
| # Пустой репозиторий для работы с Java кодом в Android Studio | ||
|
|
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,89 @@ | ||
| import java.text.DecimalFormat; | ||
| import java.util.ArrayList; | ||
| import java.util.List; | ||
| import java.util.Scanner; | ||
|
|
||
| public class BillCalculator { | ||
| private static final DecimalFormat decimalFormat = new DecimalFormat("0.00"); | ||
| private List<String> items; | ||
| private List<Double> prices; | ||
|
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. 🍏 Можно создать специальный класс для хранения товаров/блюд, например, Product с полями name и price. |
||
| private int numPeople; | ||
|
|
||
| public BillCalculator() { | ||
| items = new ArrayList<>(); | ||
| prices = new ArrayList<>(); | ||
| numPeople = 0; | ||
| } | ||
|
|
||
| public void start() { | ||
| enterNumPeople(); | ||
| addItems(); | ||
| displayResults(); | ||
| } | ||
|
|
||
| private void enterNumPeople() { | ||
| Scanner scanner = new Scanner(System.in); | ||
| System.out.println("Введите количество людей:"); | ||
| while (true) { | ||
| try { | ||
| numPeople = Integer.parseInt(scanner.nextLine()); | ||
|
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.nextInt() |
||
| if (numPeople == 1) { | ||
| System.out.println("Нет смысла считать и делить на 1 человека. Введите корректное количество гостей."); | ||
| } else if (numPeople < 1) { | ||
| System.out.println("Некорректное значение. Введите корректное количество гостей."); | ||
|
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 { | ||
| break; | ||
| } | ||
| } catch (NumberFormatException e) { | ||
| System.out.println("Некорректное значение. Введите корректное количество гостей."); | ||
|
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. 🍏 Рекомендую выносить повторяющиеся строки в константы. Тогда при необходимости изменений их нужно будет произвести в одном месте, а не по всему приложению |
||
| } | ||
| } | ||
| } | ||
|
|
||
| private void addItems() { | ||
| Scanner scanner = new Scanner(System.in); | ||
| while (true) { | ||
| System.out.println("Введите название товара или 'Завершить', чтобы завершить добавление товаров:"); | ||
| String item = scanner.nextLine(); | ||
| if (item.equalsIgnoreCase("завершить")) { | ||
| break; | ||
| } | ||
| double price; | ||
| while (true) { | ||
| try { | ||
| System.out.println("Введите стоимость товара (в формате рубли.копейки):"); | ||
| price = Double.parseDouble(scanner.nextLine()); | ||
| if (price <= 0) { | ||
| System.out.println("Некорректная стоимость товара. Введите положительное значение."); | ||
| } else { | ||
| break; | ||
| } | ||
| } catch (NumberFormatException e) { | ||
| System.out.println("Некорректная стоимость товара. Введите корректное значение."); | ||
| } | ||
| } | ||
| items.add(item); | ||
| prices.add(price); | ||
| System.out.println("Товар успешно добавлен."); | ||
| } | ||
| } | ||
|
|
||
| private void displayResults() { | ||
| System.out.println("\nДобавленные товары:"); | ||
| for (int i = 0; i < items.size(); i++) { | ||
| System.out.println(items.get(i) + " - " + decimalFormat.format(prices.get(i)) + " рублей"); | ||
|
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. 🍏 При печати в памяти будут создаваться промежуточные строки из-за множественного использования оператора "+". Можно использовать StringBuilder, который сформирует только результирующую строку, или String.format(). Например: |
||
| } | ||
| double totalAmount = 0; | ||
| for (double price : prices) { | ||
| totalAmount += price; | ||
| } | ||
| double perPersonAmount = totalAmount / numPeople; | ||
| System.out.println("\nСумма, которую должен заплатить каждый человек:"); | ||
| System.out.println(decimalFormat.format(perPersonAmount) + " рубля"); | ||
| } | ||
|
|
||
| public static void main(String[] args) { | ||
| BillCalculator calculator = new BillCalculator(); | ||
| calculator.start(); | ||
| } | ||
| } | ||
This file was deleted.
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.
🍏 Переменные, ссылки на которые не изменяться, можно объявить final, чтобы защитить от случайного изменения.