Skip to content
59 changes: 59 additions & 0 deletions src/main/java/Calculator.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import java.util.ArrayList;

public class Calculator {
public Calculator(int personCount, ArrayList<Dish> dishesList) {
calculate(personCount, dishesList);
}

private void calculate(int personCount, ArrayList<Dish> dishesList){
showDishList(dishesList);
totalPriceForPerson(personCount, dishesList);
}

private void showDishList(ArrayList<Dish> dishesList){
System.out.println("Добавленные товары:");
int a = 0;
String x = "рубль";
String y = "рубля";
String z = "рублей";
for(int i = 0; i < dishesList.size(); i++){
a = dishesList.get(i).getPrice().intValue();
String ending = String.valueOf(a);
ending = ending.substring(ending.length() - 1);
if(ending.equals("1")){
ending = x;
}
if(ending.equals("2") || ending.equals("3") || ending.equals("4")){
ending = y;
}
if(ending.equals("5") || ending.equals("6") || ending.equals("7") || ending.equals("8") || ending.equals("9") ||ending.equals("0")){
ending = z;
}
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Эти проверки дублируются тут и в totalPriceForPerson

System.out.println("Позиция: " + dishesList.get(i).getName() + " Цена: " + String.format("%.2f", dishesList.get(i).getPrice()) + " " + ending);
}
}

private void totalPriceForPerson(int personCount, ArrayList<Dish> dishesList){
Double totalPrice = 0.0;
for(int i = 0; i < dishesList.size(); i++){
totalPrice = totalPrice + dishesList.get(i).getPrice();
}
totalPrice = totalPrice / personCount;
int a = totalPrice.intValue();
String x = "рубль";
String y = "рубля";
String z = "рублей";
String ending = String.valueOf(a);
ending = ending.substring(ending.length() - 1);
if(ending.equals("1")){
ending = x;
}
if(ending.equals("2") || ending.equals("3") || ending.equals("4")){
ending = x;
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Тут опечатался, должно быть y

}
if(ending.equals("5") || ending.equals("6") || ending.equals("7") || ending.equals("8") || ending.equals("9") ||ending.equals("0")){
ending = z;
}
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️Немного некорректно рассчитывается окончание. Получается если цена будет 14 рублей, метод вернет рубля. Правильный алгоритм звучит так - Проверить лежит ли остаток от деления на 100 в интервале от 11 до 14 включительно, если да, то возвращаем рублей, если нет, то берем остаток от деления на 10 и поверяем, если 1 - рубль, 2-3-4 то рубля, в противном случае - рублей. То есть нужно во-первых проверять именно остаток от деления, во-вторых учесть, что числа заканчивающиеся на 11-12-13-14 и заканчивающиеся на 1-2-3-4, будут иметь разные окончания

System.out.println("Итоговая цена для каждой персоны: " + String.format("%.2f", totalPrice) + " " + ending);
}
}
60 changes: 60 additions & 0 deletions src/main/java/Dish.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import java.util.Scanner;

public class Dish {
private Double price;
private String name;

public Dish() {
setName();
setPrice();
System.out.println("Позиция успешно добавлена!");
}

public Double getPrice() {
return price;
}

public String getName() {
return name;
}

public void setName() {
Scanner scanner = new Scanner(System.in);
while(true){
System.out.println("Введите название блюда.");
String line = scanner.nextLine();
if(line.trim().isEmpty()){
System.out.println("Ничего не введено. Попробуйте снова");
continue;
}
else{
name = line;
break;
}
}
}

public void setPrice() {
Scanner scanner = new Scanner(System.in);
while(true){
System.out.println("Укажите стоимость " + name);
String line = scanner.nextLine();
if(line.trim().isEmpty()){
System.out.println("Ничего не введено. Попробуйте снова");
continue;
}
if(!line.equals(line.replaceAll("[^0-9.]", ""))){
System.out.println("Нужно число без букв. Попробуйте снова");
continue;
}
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

price = Double.parseDouble(line);
if(price <= 0.0){
System.out.println("Цена должна быть положительной. Попробуйте снова");
continue;
}
else{
break;
}
}
}
}
56 changes: 52 additions & 4 deletions src/main/java/Main.java
Original file line number Diff line number Diff line change
@@ -1,8 +1,56 @@
public class Main {
import java.util.ArrayList;
import java.util.Scanner;

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

ArrayList<Dish> dishesList = new ArrayList<>();

int personCount = getPersonCount();

Scanner scanner = new Scanner(System.in);
String line = "";
while(true){
dishesList.add(new Dish());
System.out.println("Для добавления нового товара введите что угодно. Для завершения введите 'завершить'");
line = scanner.nextLine();
if(line.equalsIgnoreCase("завершить")){
System.out.println("Составление списка успешно завершино");
break;
}
}
Calculator calculator = new Calculator(personCount, dishesList);

}
private static int getPersonCount(){
Scanner scanner = new Scanner(System.in);
while(true){
System.out.println("На скольких человек необходимо разделить счёт?");
String line = scanner.nextLine();
if(line.trim().isEmpty()){
System.out.println("Ничего не введено. Попробуйте снова");
continue;
}
if(!line.equals(line.replaceAll("[^0-9.]", ""))){
System.out.println("Нужно целое число без букв. Попробуйте снова");
continue;
}
if(line.contains(".") || line.contains(",")){
System.out.println("Нужно целое число. Попробуйте снова");
continue;
}
int personCount = Integer.parseInt(line);
if(personCount < 2){
System.out.println("Число персон должно быть не меньше двух. Попробуйте снова");
continue;
}
else{
System.out.println("Счёт будет разделён на " + personCount + " персоны");
return personCount;
}
}
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

}
}