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
20 changes: 20 additions & 0 deletions src/main/java/Calculator.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import java.util.ArrayList;
public class Calculator {
ArrayList<Float> prices = new ArrayList<>();
Formatter rub = new Formatter();
public void addPrice(float price){
prices.add(price);
}
public void samib() {
float sum = 0;
for(Float price : prices) {
sum += price;
}
int result2;
result2 = (int)Math.floor(sum / Main.quantity);
float result = sum / Main.quantity;
rub.formatRub(result2);
Comment on lines +14 to +16
Copy link
Copy Markdown

@IvanGusevE IvanGusevE Apr 4, 2024

Choose a reason for hiding this comment

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

Предлагаю передавать количество quantity в качестве дополнительного параметра в функцию samib. Такой подход делает класс Calculator более независимым от класса Main, что повышает его переиспользуемость.

Также лучше перенести логику округления в функцию класса Formatter, поскольку он отвечает за форматирование данных и их представление.

String format = "С каждого по %.2f %s";
System.out.println(String.format(format, result, Formatter.padezh));
}
}
15 changes: 15 additions & 0 deletions src/main/java/Formatter.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
public class Formatter {
public static String padezh;
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Вместо использования переменной padezh лучше получать отформатированную строку через метод formatRub (поскольку метод уже возвращает строку). Это позволит избавиться от лишней переменной и уменьшит сложность класса, так как логика форматирования будет инкапсулирована в соответствующем методе.

public String formatRub(int result2) {
int x = result2 % 10;
int y = result2 % 100;
if(x == 0 || (x >= 5 && x <= 9) || (y>= 11 && y <= 14)){
padezh = "рублей";
}else if (x == 1 ) {
padezh = "рубль";
}else {
padezh = "рубля";
}
Comment on lines +6 to +12
Copy link
Copy Markdown

@IvanGusevE IvanGusevE Apr 4, 2024

Choose a reason for hiding this comment

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

Условие (x >= 5 && x <= 9) можно сократить до x >= 5, т.к. переменная x никогда не будет больше 10.
Также если у тебя получится избавится от свойства класса padezh, можно будет переписать метод следующим образом:

        if(...){
            return "рублей";
        }else if (x == 1 ) {
            return "рубль";
        }else {
            return  "рубля";
        }

Но еще лучше будет попробовать переписать эти условия на switch ... case

return padezh;
}
}
56 changes: 54 additions & 2 deletions src/main/java/Main.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,58 @@

import java.util.Scanner;
public class Main {

public static int quantity;
public static void main(String[] args) {
System.out.println("Hello world!");
Scanner scanner = new Scanner(System.in);
Products products = new Products();
Calculator prices = new Calculator();
String product;
float price;

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

String end = "";
while (!end.equalsIgnoreCase("Завершить")) {
System.out.println("Введите название блюда");
product = scanner.nextLine();
products.addProduct(product);
while (true) {
System.out.println("Введите цену блюда");
if (scanner.hasNextFloat() ) {
price = scanner.nextFloat();
scanner.nextLine();
if(price > 0) {
prices.addPrice(price);
break;
} else {
System.out.println("Введите цену больше 0");
}
} else {
System.out.println("введите цифровое значение");
scanner.nextLine();
}
}
System.out.println("Товар успешно добавлен");
System.out.println("Добавить новый товар или завершить?");
end = scanner.nextLine();
}
System.out.println("Добавленные товары:");
products.outputProducts();
prices.samib();
scanner.close();
}
}
12 changes: 12 additions & 0 deletions src/main/java/Products.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import java.util.ArrayList;
public class Products {
ArrayList<String> products = 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.

Было бы лучше создать отдельный класс Product, содержащий следующие поля:

  • name - имя продукта;
  • price - его цена.

Таким образом, вместо списка строк мы будем использовать список объектов класса Product. Это также позволит избавиться от необходимости хранить отдельный список prices в классе Calculator.

public void addProduct(String product){
products.add(product);
}
public void outputProducts() {
for(String product : products) {
System.out.println(product);
}
}
}