/
Nicholas
/
java_basics
Обзор
Документация
Войти
/
Nicholas
/
java_basics
Код
Запросы
0
Пакеты
0
Релизы
0
Аналитика
Безопасность
master
ObjectsAndClasses_Methods/src/Basket.java
122 строки
3 KB
Nicholay Sokolovsky
Basket static variables and methods (additional functionality)
06 авг 2023, 11:07
06 авг 2023, 11:07
d67246a
Код
Авторство
О чём код?
public class Basket { private static int count = 0; private static int allBasketsPrice = 0; private static int allBasketsItems = 0; private String items; private int itemsCount = 0; private int totalPrice = 0; private int limit; private double totalWeight = 0; public Basket() { increaseCount(1); items = ""; this.limit = 1000000; } public Basket(int limit) { this(); this.limit = limit; } /* Если дадим возможность заполнять корзину сразу строками, то потеряем возможность считать кол-во товаров в каждой корзине. (либо надо парсить строки, чтобы вытаскивать из них кол-во товара в штуках) public Basket(String items, int totalPrice) { this(); this.items = this.items + items; this.totalPrice = totalPrice; } */ public static int getCount() { return count; } public static void increaseCount(int count) { Basket.count = Basket.count + count; } public static void increaseAllBasketsPrice(int price) { allBasketsPrice = allBasketsPrice + price; } public static void increaseAllBasketsItems(int itemCount) { allBasketsItems = allBasketsItems + itemCount; } public static int getAllBasketsAvgItemPrice() { return allBasketsItems == 0 ? 0 : allBasketsPrice / allBasketsItems; } public static int getAllBasketsAvgBasketPrice() { return count == 0 ? 0 : allBasketsPrice / count; } public void add(String name, int price) { add(name, price, 1); } public void add(String name, int price, int count, double weight) { add(name, price, count); totalWeight = totalWeight + weight; } public void add(String name, int price, int count) { boolean error = contains(name); if (totalPrice + count * price >= limit) { error = true; } if (error) { System.out.println("Error occured :("); return; } items = items + "\n" + name + " - " + count + " шт. - цена " + price + " руб."; totalPrice = totalPrice + count * price; itemsCount = itemsCount + count; increaseAllBasketsItems(count); increaseAllBasketsPrice(count * price); } public void clear() { increaseAllBasketsItems(-itemsCount); increaseAllBasketsPrice(-totalPrice); items = ""; itemsCount = 0; totalPrice = 0; totalWeight = 0; } public int getItemsCount() { return itemsCount; } public int getItemPositionsCount() { return items.split("\r\n|\r|\n").length - 1; //Считаем уол-во строк, оно же кол-во позиций товаров в корзине } public int getTotalPrice() { return totalPrice; } public double getTotalWeight() { return totalWeight; } public boolean contains(String name) { return items.contains(name); } public void print(String title) { System.out.print(title); if (items.isEmpty()) { System.out.println("Корзина пуста"); } else { System.out.println(items); } } }