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

public class Calculator {
final private int numbPeople;
Scanner scanner = new Scanner(System.in);
final private ArrayList<Product> arrProducts = new ArrayList<>();

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

👍 Хорошее применение списков!


Calculator(int numbPeople) {
this.numbPeople = numbPeople;
addProduct();
}

private void addProduct() {
while (true) {
arrProducts.add(new Product());
System.out.println("Товар \""
+ arrProducts.get(arrProducts.size() - 1).getProductName()
+ "\" успешно добавлен. \n Введите \"Завершить\" чтобы перейти к подсчёту "
+ "или нажмите \"Enter\" чтобы продолжить работу.");
if (isFinish()) {
finalCount();
break;
}
}
}

private void finalCount() {
double sum = 0, res;

StringBuilder resStrB = new StringBuilder("Добавленные товары: \n");

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!


for (Product product : arrProducts) {
resStrB.append( product.getProductName()
.concat(": ")
.concat(
String.format("%.2f", product.getProductPrice()))
.concat(Formatter.getEndWord(product.getProductPrice()))
.concat(",\n"));
sum += product.getProductPrice();

}

System.out.println(resStrB.substring(0, resStrB.length() - 2) + ".");
res = sum / numbPeople;
System.out.println("--------");
System.out.println(
String.format("ИТОГ: каждый должен заплатить %.2f ", res) +
Formatter.getEndWord(res));

}

private boolean isFinish() {
String tmpStr = scanner.nextLine().trim();
return "завершить".equalsIgnoreCase(tmpStr);

}



}
30 changes: 30 additions & 0 deletions src/main/java/Formatter.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
public class Formatter {
final private static String[] strRub = {
" рубль",
" рубля",
" рублей"
};

public static String getEndWord(double productPrice) {
int intPrice = (int) productPrice;

if (intPrice >= 5 && intPrice <= 19) {
return strRub[2];
} else {
switch (intPrice % 10) {
case 2:
case 3:
case 4:
return strRub[1];
case 0:
case 5:
case 6:
case 7:
case 8:
case 9:
return strRub[2];
}
}
return strRub[0];
}
}
30 changes: 29 additions & 1 deletion src/main/java/Main.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,34 @@

import java.util.Scanner;

public class Main {

public static void main(String[] args) {
System.out.println("Hello world!");
System.out.println("\t\tКАЛЬКУЛЯТОР СЧЁТА\n");
new Calculator(getSumPeople());

System.exit(0);
}

private static int getSumPeople() {
Scanner scanner = new Scanner(System.in);
int numb;
String strIn;

System.out.println("На скольких человек необходимо разделить счёт? Введите число: ");

while (true) {
strIn = scanner.nextLine();

if (strIn.matches("^[0-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.

⏫ Интересный способ использовать регулярку для проверки на вводимое число. Такое регульрное выражение можно заменить на более лаконичное ^\\d+$

numb = Integer.parseInt(strIn.trim());
if (numb <= 1)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⏫ Строчка с if немного съехала относительно остального кода внутри этого блока.

В IDEA есть удобный инструмент автоматического форматирования кода. Для этого достаточно нажать на горячие клавиши Ctrl+Alt+L (Command+Option+L)

System.out.println(numb + " - некорректное значение. Введите количество человек:");
else
return numb;
} else
System.out.println("Неизвестный символ. Введите число:");
}
}

}
38 changes: 38 additions & 0 deletions src/main/java/Product.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import java.util.Scanner;

public class Product {
final private String title;
final private double price;

Scanner scanner = new Scanner(System.in);

Product() {
title = findTitle();
price = findPrice();

}

private String findTitle() {
System.out.println("Введите название товара: ");
return scanner.nextLine();
}

private double findPrice() {
System.out.println("Введите его стоимость в формате \"рубли.копейки\": ");
do {
String tmpStr = scanner.nextLine().trim();
if (tmpStr.matches("^[0-9]+\\.[0-9]{2}?$"))

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⏫ В данном случае мы слишком завязаны на формат "рубли.копейки". Было бы лучше добавить проверку вводимой строки через nextDouble. Но использование регулярного выражения - очень интересный способ)

return Double.parseDouble(tmpStr);
System.out.println("Неверный ввод. Пожалуйста, введите стоимость в формате \"рубли.копейки\": ");
} while (true);
}

String getProductName() {
return title;
}

double getProductPrice() {
return price;
}

}