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
7 changes: 7 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -1 +1,8 @@
# Пустой репозиторий для работы с Java кодом в Android Studio

Вся логика взаимодействия с пользователем описана в классе Main:
- Программа запрашивает у пользователя, на скольких человек разделить счёт и проверяет данные на корректность с помощью if/else, а также try/catch.
- При успешном вводе количества человек (>1) на вход принимает информацию о товарах. Эта информация попадает в класс Calculator.
- Класс Calculator состоит из основных методов: подсчёт общей стоимости для каждого пользователя, добавление в список товаров, а также вывод списка на экран после добавления всех.
- Каждый товар - объект класса Product c двумя полями: "название товара" и "цена", а также конструктором.
- Класс Formatter состоит из двух основных методов, которые помогают с выводом на экран: округление суммы до двух знаков после запятой и склонение валюты "рубль".
28 changes: 28 additions & 0 deletions src/main/java/Calculator.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
public class Calculator {
int users;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Рекомендация: Форматирование кода - в Java принят немного другой стиль форматирования кода. Если не вдаваться в детали, то легко и быстро отформатировать код в Android Studio можно следующей комбинацией клавиш: в Windows Ctrl + Alt + L , в MacOs ⌘ + ⌥ + L.

double totalCost = 0.00;
String listOfProducts = "";

Calculator(int users) {
this.users = users;
}

void addProduct(Product product) {
totalCost += product.costOfProduct;
// формируем список продуктов заранее
Formatter formatter = new Formatter();
listOfProducts = listOfProducts + "\n" + product.nameOfProduct + " - "
+ formatter.roundingTheDouble(product.costOfProduct)
+ formatter.displayCurrency(product.costOfProduct);
System.out.println("Товар успешно добавлен.");
}

void displayProducts() {
System.out.println("Добавленнные товары:" + listOfProducts);
}

double calculateScoreForEachPerson() {
return totalCost / users;
}

}
25 changes: 25 additions & 0 deletions src/main/java/Formatter.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
public class Formatter {
String roundingTheDouble(double totalCostForEach) {
return String.format("%.2f", totalCostForEach);
}

String displayCurrency(double totalCostForEach) {
String currency;
String standardCurrency = " рублей.";
int cost = (int) Math.floor(totalCostForEach);
int preCalcCost = cost % 100;
switch (cost % 10) {
case 1 -> {
if (preCalcCost == 11) currency = standardCurrency;
else currency = " рубль.";
}
case 2, 3, 4 -> {
if (preCalcCost >= 12 && preCalcCost <= 14)
currency = standardCurrency;
else currency = " рубля.";
}
default -> currency = standardCurrency;
}
return currency;
}
}
59 changes: 58 additions & 1 deletion src/main/java/Main.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,63 @@
import java.util.InputMismatchException;
import java.util.Scanner;

public class Main {

public static void main(String[] args) {
System.out.println("Hello world!");
Scanner scanner = new Scanner(System.in);
Formatter formatter = new Formatter();
while (true) {
System.out.println("На скольких человек разделить счёт?");
try {
int persons = scanner.nextInt();
scanner.nextLine();
if (persons < 1) System.out.println("Ошибка: некорректное число пользователей.");
else if (persons == 1) System.out.println("Ошибка: делить ничего не требуется.");
else {
System.out.println("Успех: корректное число пользователей, можете воспользоваться калькулятором.");
Calculator calculator = new Calculator(persons);
while (true) {
System.out.println("Введите название товара:");
String nameOfProduct = scanner.nextLine().trim();
if (nameOfProduct.isEmpty()) {
System.out.println("Ошибка: некорректная длина названия товара.");
} else {
double costOfProduct;
while (true) {
System.out.println("Введите стоимость товара (Формат: рубли,копейки):");
try {
costOfProduct = scanner.nextDouble();
scanner.nextLine();
if (costOfProduct <= 0.00) {
System.out.println("Ошибка: некорректная цена, введите положительное число.");
} else break;
} catch (InputMismatchException e) {
System.out.println("Ошибка: недопустимый тип ввода.");
scanner.nextLine();
}
}
// Можно создавать и добавлять в список новый продукт
Product product = new Product(nameOfProduct, costOfProduct);
calculator.addProduct(product);

System.out.println("Добавить ещё товар?");
String usersAnswer = scanner.nextLine();
if (usersAnswer.equalsIgnoreCase("завершить")) break;
}
}
// Вывод результатов пользователю
calculator.displayProducts();
double scoreForEachPerson = calculator.calculateScoreForEachPerson();
System.out.println("Итоговая стоимость: "
+ formatter.roundingTheDouble(scoreForEachPerson)
+ formatter.displayCurrency(scoreForEachPerson));
break;
}
} catch (InputMismatchException e) {
System.out.println("Ошибка: недопустимый тип ввода. Требуется ввести целое число.");
scanner.nextLine();
}
}
scanner.close();
}
}
9 changes: 9 additions & 0 deletions src/main/java/Product.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
public class Product {
String nameOfProduct;
double costOfProduct;

Product(String nameOfProduct, double costOfProduct) {
this.nameOfProduct = nameOfProduct;
this.costOfProduct = costOfProduct;
}
}