Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1 +1 @@
# Пустой репозиторий для работы с Java кодом в Android Studio

89 changes: 89 additions & 0 deletions src/main/java/BillCalculator.java
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;
Comment on lines +8 to +9

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🍏 Переменные, ссылки на которые не изменяться, можно объявить final, чтобы защитить от случайного изменения.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The 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());

Copy link
Copy Markdown

Choose a reason for hiding this comment

The 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("Некорректное значение. Введите корректное количество гостей.");

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🍏 Круто было бы подсказать пользователю, в каком диапазоне от него ожидается ввод)

} else {
break;
}
} catch (NumberFormatException e) {
System.out.println("Некорректное значение. Введите корректное количество гостей.");

Copy link
Copy Markdown

Choose a reason for hiding this comment

The 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)) + " рублей");

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🍏 При печати в памяти будут создаваться промежуточные строки из-за множественного использования оператора "+". Можно использовать StringBuilder, который сформирует только результирующую строку, или String.format(). Например:

System.out.println(String.format("%s - %s рублей", items.get(i), decimalFormat.format(prices.get(i)) )

}
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();
}
}
6 changes: 0 additions & 6 deletions src/main/java/Main.java

This file was deleted.