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
33 changes: 33 additions & 0 deletions src/main/java/Calculator.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@


public class Calculator {

String list = "";
float totalPrice = 0;

RubleFormatter formatter = new RubleFormatter();

void add(float price) {
totalPrice += price;
}

void writeToTheList(String nameOfProduct, float priceOfProduct) {
list += nameOfProduct.trim().toLowerCase();
list += " ";
list += priceOfProduct;
list += "\n";
}

void showCheck(int numberOfUsers) {
System.out.println("Добавленные товары:");
System.out.println(list);
String messageTemplateTotalPrice = "Итоговая сумма: %.2f %s.";
String messageTemplateResult = "Каждый должен заплатить %.2f %s.";

String formattedUnit = formatter.formatUnit(totalPrice);
System.out.println(String.format(messageTemplateTotalPrice, totalPrice, formattedUnit));

formattedUnit = formatter.formatUnit(totalPrice / numberOfUsers);
System.out.println(String.format(messageTemplateResult, totalPrice / numberOfUsers, formattedUnit));
}
}
98 changes: 96 additions & 2 deletions src/main/java/Main.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,100 @@


import java.util.InputMismatchException;
import java.util.Scanner;

public class Main {
public static void main(String[] args) {
System.out.println("Hello world!");

int numberOfUsers = -1;

Scanner scanner = new Scanner(System.in); // Создаем экземпляр класса Scanner.
Calculator calculator = new Calculator();

numberOfUsers = getNumberOfPeople(scanner);
getProductsInfo(scanner, calculator);
calculator.showCheck(numberOfUsers);

scanner.close(); // Закрываем Scanner по завершении работы.
}


public static int getNumberOfPeople(Scanner scan) {
int numb = -1;
while (true) {
System.out.println("Введите, на скольких человек необходимо разделить счёт");

numb = getInt(scan);
if (numb > 1) {
break;
} else {
System.err.println("Некорректное число");
}
}
return numb;
}


public static void getProductsInfo(Scanner scan, Calculator calculator) {
while (true) {
String nameOfProduct = "";
float priceOfProduct = 0;

System.out.println("Введите название товара");
nameOfProduct = scan.next();


while (priceOfProduct <= 0) {

System.out.println("Введите цену товара");

priceOfProduct = getFloat(scan);

if (priceOfProduct > 0) {
calculator.add(priceOfProduct);
calculator.writeToTheList(nameOfProduct, priceOfProduct);
System.out.println("Товар успешно добавлен");
} else {
System.err.println("Некорректная цена!");
}

}

System.out.println("Продолжить ввод товаров? Введите \"Завершить\"," +
" если хотите окончить ввод товаров, или любой символ, если хотите продолжить ввод");
String command = scan.next();

if (command.equalsIgnoreCase("Завершить")) {
break;
}
}
}



public static float getFloat(Scanner scan) {
try {
float number = scan.nextFloat();

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Тоже самое только hasNextFloat

return number;
} catch (InputMismatchException e) {
scan.nextLine();
return 0;
}
}
}

public static int getInt(Scanner scan) {
try {
int number = scan.nextInt();

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 есть удобный метод hasNextInt, можно сразу узнать без дополнительных проверок возможно ли интерпретировать строку как int

return number;
} catch (InputMismatchException e) {
scan.nextLine();
return 0;
}
}


}




Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Лишние отступы

28 changes: 28 additions & 0 deletions src/main/java/RubleFormatter.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
public class RubleFormatter {


String formatUnit(float price) {
/*
Здесь форматируем окончание валюты, в зависимости от цены.
Если предпоследняя цифра "1", то возвращаем рублей
Иначе если последняя 1 - рубль, 2,3,4 - рубля, 5,6,7,8,9,0 - рублей
*/

int formattedPrice = (int) Math.floor(price);

if (formattedPrice % 100 / 10 == 1) {
return "рублей";
}

switch (formattedPrice % 10) {
case 1:
return "рубль";
case 2:
case 3:
case 4:
return "рубля";
default:
return "рублей";
}
}
}