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

public class Calculator {
private ArrayList<ProductAndPrice> bill = new ArrayList<>();
private double total = 0;
private final int numberPerson;
public Calculator(int numberPerson) {
this.numberPerson = numberPerson;
}

/*Метод add принимает на вход строку.
Если входных данных валидны преобразует строку в параметры,
создает на их основе экземпляр класса ProductAndPrice и
добавляет последний в массив bill; при успешном выполнении возвращает true.
Если переданный в метод аргумент не валидный возвращает false*/
public boolean add(String s){
int lastSpace = s.lastIndexOf(" ");

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⏫ Можно использовать String[] words = s.split(" "); так сразу разделится по словам

if (lastSpace == -1){
return false;
}
String name = s.substring(0, lastSpace);
String price = s.substring(lastSpace + 1);
if(Pattern.matches("^(0|\\d+)[.]\\d\\d$", price.trim())){
double i = Double.parseDouble(price);
bill.add(new ProductAndPrice(name, i));
total += i;
return true;
} else {
return false;
}
}

/* Метод выводит на экран данные класса Calculator, в соответсвии с заданным условием*/
public void printBill(){
StringBuilder sb = new StringBuilder("Добавленные товары:\n");
for(int i = 0; i < bill.size(); i++){
sb.append(bill.get(i).getName()).append(" ").append(bill.get(i).getPrice()).append("\n");
}
String average = String.format("%.2f", total/(double)numberPerson);
sb.append("Каждый человек должен заплатить ").append(average).append(" ").append(declinationOfRub(total / (double) numberPerson));
System.out.println(sb);
}

/*Метод возвращает слово "рубль" в склонении, соответсвующим целочисленной части
переданному ему числа */
public String declinationOfRub(double n){
int num = (int) n;
int preLastDigit = num % 100 / 10;
if (preLastDigit == 1)
{
return "рублей";
}
switch (num % 10)
{
case 1:
return "рубль";
case 2:
case 3:
case 4:
return "рубля";
default:
return "рублей";
}
}
}
37 changes: 36 additions & 1 deletion src/main/java/Main.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,41 @@
import java.util.Scanner;

public class Main {
public static void main(String[] args) {
System.out.println("Hello world!");
Scanner scanner = new Scanner(System.in);
int numberPerson;

System.out.println("На скольких человек необходимо разделить счёт?");
while (true) {
if(scanner.hasNextInt()){
int a = scanner.nextInt();
if(a <= 1){
System.out.println("Введите корректное количество человек.");
} else {
numberPerson = a;
break;
}
} else {
System.out.println("Введите корректное количество человек.");
scanner.next();
}
}

Calculator calculator = new Calculator(numberPerson);

System.out.println("Введите через пробел название товара и его стоимость.\nCтоимость в формате 'рубли.копейки'");
while (true) {

@SeveNChaK SeveNChaK Apr 26, 2023 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⏫ Выводится лишняя строчка про ошибку
image

String s = scanner.nextLine();
if (s.equalsIgnoreCase("завершить")) {
break;
}
if (calculator.add(s)) {
System.out.println("Товар успешно добавлен в корзину.\nЖелаете продолжить?\nДля расчета введите слово 'завершить'.");
} else {
System.out.println("Введены некорректные данные, повторите попытку");
}
}
scanner.close();
calculator.printBill();
}
}
14 changes: 14 additions & 0 deletions src/main/java/ProductAndPrice.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
public class ProductAndPrice {
private final String name;
private final Double price;
public ProductAndPrice(String name, Double price) {
this.name = name;
this.price = price;
}
public String getName() {
return name;
}
public Double getPrice() {
return price;
}
}