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
27 changes: 27 additions & 0 deletions src/main/java/BillCalculator.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
public class BillCalculator {
double sumAllProducts = 0;
StringBuilder allProductNames = new StringBuilder();

public void addProduct(String name, double price) {
if (0 < allProductNames.length())
allProductNames.append("\n");
allProductNames.append(name);
sumAllProducts += price;

System.out.println("Товар \"" + name + "\" успешно добавлен!");
}

public void showProductsList() {
System.out.println(allProductNames.toString());
}

public double splitAllSumBetweenGuests(int countGuests) {
if (countGuests >= 1)
return sumAllProducts / ((double) countGuests);
else {
System.out.println("Ошибка! Неверное число гостей!");
return 0;
}
}

}
78 changes: 75 additions & 3 deletions src/main/java/Main.java
Original file line number Diff line number Diff line change
@@ -1,8 +1,80 @@
// dev branch for Y.Practicum

import java.util.Scanner;

public class Main {

private static final Scanner scanner = new Scanner(System.in);

public static int getGuestsCount() {
int countGuests = 0;
do {
while (!scanner.hasNextInt()) {
System.out.println("Ошибка. Вы ввели не целое число гостей, попробуйте ещё раз");
scanner.nextLine();
}
countGuests = scanner.nextInt();
if (countGuests > 1) {
scanner.nextLine(); // чтобы '/n' пропустить вконце числа
break;
} else if (countGuests == 1) {
System.out.println("Ошибка. Вы ввели только одного гостя, а программа " +
"рассчитана на большее число гостей, попробуйте ещё раз");
} else {
System.out.println("Ошибка. Вы ввели некорректное количество гостей, " +
"попробуйте ещё раз");
}
} while (true);
return countGuests;
}

public static void main(String[] args) {
// ваш код начнется здесь
// вы не должны ограничиваться только классом Main и можете создавать свои классы по необходимости
System.out.println("Привет Мир");

System.out.println("Введите количество человек, " +
"на которых нужно разделить счёт");
int countGuests = getGuestsCount();

BillCalculator billCalc = new BillCalculator();

while (true) {
System.out.println("Введите название товара");
String productName = scanner.nextLine();
System.out.println("Введите стоимость товара в формате \"рубли,копейки\"");
double productPrice = 0;
do {
while (!scanner.hasNextDouble()) {
System.out.println("Ошибка. Вы ввели некорректную стоимость, попробуйте ещё раз");
scanner.nextLine();
}
productPrice = scanner.nextDouble();
if (productPrice < 0) {
System.out.println("Ошибка. Вы ввели отрицательную стоимость, попробуйте ещё раз");
} else {
scanner.nextLine(); // чтобы '/n' пропустить вконце числа
break;
}
} while (true);

billCalc.addProduct(productName, productPrice);

System.out.println("Если Вы хотите добавить ещё один товар, то введите любой символ. " +
"А если хотите завершить ввод товаров, то введите команду \"Завершить\" в " +
"любом регистре");
String commandName = scanner.nextLine();
if (commandName.equalsIgnoreCase("Завершить")) {
break;
}
}
System.out.println("Добавленные товары:");
billCalc.showProductsList();

System.out.println("Общая сумма чека равна " +
PriceFormatter.getFormattedPriceWithRubStringByDouble(billCalc.sumAllProducts));
System.out.println(String.format("Количество гостей равно %d%n", countGuests));
double resOfSplittingBill = billCalc.splitAllSumBetweenGuests(countGuests);
System.out.println("Сумма,которую должен заплатить каждый гость равна " +
PriceFormatter.getFormattedPriceWithRubStringByDouble(resOfSplittingBill));

scanner.close();
}
}
33 changes: 33 additions & 0 deletions src/main/java/PriceFormatter.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
public class PriceFormatter {
public static String getStringFromDoubleWithToDigitsAfterPoint(double val) {
return String.format("%.2f", val);
}

public static String getCorrectRubStringByDouble(double val) {
int roundedVal = (int) (Math.floor(val));
String strVal = String.format("%d", roundedVal);
String rubString = "рублей";
if (!strVal.endsWith("11")
&& !strVal.endsWith("12")
&& !strVal.endsWith("13")
&& !strVal.endsWith("14")) {
if (strVal.endsWith("1")) {
rubString = "рубль";
} else if (strVal.endsWith("2") ||
strVal.endsWith("3") ||
strVal.endsWith("4")) {
rubString = "рубля";
}
}
return rubString;
}

public static String getFormattedPriceWithRubStringByDouble(double val) {
StringBuilder result = new StringBuilder();
result.append(getStringFromDoubleWithToDigitsAfterPoint(val))
.append(" ")
.append(getCorrectRubStringByDouble(val));

return result.toString();
}
}