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
88 changes: 88 additions & 0 deletions src/main/java/DataInput.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
import java.util.ArrayList;
import java.util.Scanner;

public class DataInput {
// Ввод кол-ва человек
public int numberOfPeople (Scanner scanner) {
int numberOfPersons;
final String STR_QUERY = "На сколько человек необходимо разделить счёт:";
final String STR_NOTE = "\nВведите целое число больше 1.";
do {
System.out.println(STR_QUERY);
while (!scanner.hasNextInt()) {
System.out.println(new StringBuilder().append("Это не целое число!").append(STR_NOTE).append("\n").append(STR_QUERY));
scanner.next();
}
numberOfPersons = scanner.nextInt();
if (numberOfPersons < 0) {
System.out.println(new StringBuilder().append("Это отрицательное число!").append(STR_NOTE));
} else if (numberOfPersons == 0) {
System.out.println(new StringBuilder().append("На 0 делить нельзя!").append(STR_NOTE));
} else if (numberOfPersons == 1) {
System.out.println(new StringBuilder().append("Нет смысла делить. Весь счет оплачивать Вам!").append(STR_NOTE));
}
} while (numberOfPersons <= 1);
return numberOfPersons;
}

// Ввод товара
public ArrayList<Product> productEntry (Scanner scanner) {
final String STR_END_INPUT = "Завершить"; // Кодовое слово для завершения ввода

ArrayList<Product> listOfProducts = new ArrayList<>(); // Массив для хранения содержимого строк счета
do {
String name;
float price;
boolean empty;
do {
// Ввод наименования товара
System.out.println("Введите наименование товара:");
name = scanner.next();
// Проверка, что строка не пустая. Кажется она не требуется (при пустой строке scanner будет повторять запрос на ввод), но на всякий случай
empty = name.isEmpty();
if (empty) {
System.out.println("У товара должно быть наименование, пустые строки не допускаются!");
}
} while (empty);
// Ввод и проверка цены
price = enteringAndCheckingPrices(scanner);
Product lb = new Product(name, price); // Создание объекта для хранения данных строки счета
listOfProducts.add(lb); // и добавление его в массив
System.out.println("Товар успешно добавлен.");
System.out.println("Хотите добавить еще один товар?\nДля завершения процесса добавления товаров введите \"Завершить\":");
} while (!scanner.next().equalsIgnoreCase(STR_END_INPUT));
return listOfProducts;
}

// Ввод и проверка цены
private float enteringAndCheckingPrices (Scanner scanner) {
final int DIGITS_AFTER_DOT = 2; // Максимальное кол-во цифр после десятичной точки

float price;
String s = "\nОжидается число больше 0 в формате \"0.00\".";
String s1 = "Введите стоимость товара:";

do {
System.out.println(s1);
// Проверка случайных символов
while (!scanner.hasNextDouble()) {
System.out.println("Это вообще не число!" + s + "\n" + s1);
scanner.next();
}
price = scanner.nextFloat();
// Проверка: цена > 0
if (price == 0) {
System.out.println("Бесплатный товар? Хмм..." + s);
} else if (price <= 0) {
System.out.println("Ого! Вы где нашли такие цены?" + s);
}
// Проверка - у цены должно быть две цифры после десятичной точки
String[] strPrice = String.valueOf(price).split("\\.", 2); // Разбиваем строку на массив из 2-х строк: целая часть и дробная
if (strPrice[1].length() > DIGITS_AFTER_DOT) { // Если в дробной части больше 2 знаков
System.out.println("Многовато копеек!" + s);
price = 0.0f;
}
} while (price <= 0);
return price;
}
}
33 changes: 33 additions & 0 deletions src/main/java/DataOutput.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import java.util.ArrayList;

public class DataOutput {
// Вывод итогов
public void outputOfResults (int numberOfPersons, ArrayList<Product> listOfProducts) {
float sumBill = 0;
System.out.println("Добавленные товары:\n"); // Заголовок
for (Product item : listOfProducts) {
float prise = item.getPrise();
sumBill = sumBill + prise;
System.out.printf("%s ..... %.2f%n", item.getName(), prise);
}
System.out.printf("---------------------" + "Итого по счету: %.2f\n%n", sumBill); // Подчеркивание и вывод итоговой суммы по счету
double fromEveryPerson = sumBill / numberOfPersons;
System.out.printf("\nГоспода, с Вас по: %.2f %s%n", fromEveryPerson, rubles(fromEveryPerson)); // Вывод доли счета
}

// Правильное окончание слова "рубль"
private String rubles (double fromEveryPerson) {
int lastDigit = ((int) fromEveryPerson) % 10; // Получаем последнюю цифру целой части
String s;
if (lastDigit == 0) {
s = "рублей";
} else if (lastDigit == 1) {
s = "рубль";
} else if (lastDigit < 5) {
s = "рубля";
} else {
s = "рублей";
}
return s;
}
}
13 changes: 12 additions & 1 deletion src/main/java/Main.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,17 @@

import java.util.ArrayList;
import java.util.Scanner;

public class Main {
public static void main(String[] args) {
System.out.println("Hello world!");
Scanner scanner = new Scanner(System.in);
DataInput dataInput = new DataInput();
// Запрос кол-ва участников
int numberOfPersons = dataInput.numberOfPeople(scanner);
// Ввод товара
ArrayList<Product> listOfProducts = dataInput.productEntry(scanner);
scanner.close(); // Закрыть сканер

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

👏 Круто, что не забываешь завершить работу со сканнером

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

Спасибо

// Вывод счета, итога и причетающейся каждому суммы
new DataOutput().outputOfResults(numberOfPersons, listOfProducts);
}
}
11 changes: 11 additions & 0 deletions src/main/java/Product.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
public class Product {
private String name;
private float price;

public Product(String name, float price) {
this.name = name;
this.price = price;
}
public String getName() { return name; }
public float getPrise() { return price; }
}