Добавление статических переменных и реализация статических методов

Столкнулся с проблемой. 1)Добавьте две статические переменные для хранения общей стоимости и общего количества всех товаров во всех корзинах. 2)Реализуйте статические методы, которые будут увеличивать значения этих переменных при добавлении в корзину новых товаров. Переменные basketCount и totalCost добавил, количество корзин в консоль выводит. А вот с общей стоимостью товаров проблема. Пробовал static поставить для totalPrice, после этого в консоль выводится общая стоимость, но с каждой корзиной она увеличивается, и для каждой корзины выдает стоимость больше, чем есть товаров в ней(то есть totalPrice(1-й корзины) + totalPrice(2-й корзины и т.д.). А мне необходимо, чтобы общую стоимость товаров для каждой корзины не менялось, и выводило общую стоимость всех товаров во всех корзинах. Рад любой помощи.

public class Basket {

    private static int count = 0;
    private static int basketCount = 0;
    private String items = "";
    private int totalPrice = 0;
    private double totalWeight = 0;
    private int limit;
    private static int totalCost = 0;

    public Basket() {
        increaseCount(1);
        basketCount = basketCount + 1;
        items = "Список товаров:";
        this.limit = 1000000;
    }

    public Basket(int limit) {
        this();
        this.limit = limit;
    }

    public Basket(String items, int limit) {
        this();
        this.items = this.items + items;
        this.limit = limit;
        this.totalPrice = this.totalPrice + totalPrice;
    }

    public static int getCount() {
        return count;
    }

    public static void increaseCount(int count) {
        Basket.count = Basket.count + count;
    }

    public void add(String name, int price) {
        add(name, price, 1);
    }

    public void add(String name, int price, int count) {
        boolean error = false;
        if (contains(name)) {
            error = true;
        }

        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;
        }

    public void add(String name, int price, double weight)
    {
        add(name, price, 1, weight);
    }

    public void add(String name, int price, int count, double weight)
    {
        add(name, price, 1);
        totalWeight = totalWeight + count * weight;
        }

    public void clear() {
        items = "";
        totalPrice = 0;
        totalWeight = 0;
    }

    public int getTotalPrice() {
        return totalPrice;
    }

    public static int getTotalCost() {
        return totalCost;
    }

    public static int getTotalCount() {
        return basketCount;
    }

    public double getTotalWeight() {
        return totalWeight;
    }

    public boolean contains(String name) {
        return items.contains(name);
    }

    public void print(String title) {
        System.out.println(title);
        if (items.isEmpty()) {
            System.out.println("Корзина пуста");
        } else {
            System.out.println(items);
            System.out.println("Общая стоимость товаров в корзине " + totalPrice + " рублей;");
            System.out.println("Общий вес товаров в корзине " + totalWeight + " кг;");
        }
    }
}

И тестовый класс Main:

public class Main {

    public static void main(String[] args) {
        Basket vasyaBasket = new Basket(100);
        vasyaBasket.add("Молоко", 40,1,50);
        vasyaBasket.print("Корзина Васи");
        System.out.println();

        Basket mashaBasket = new Basket(200);
        mashaBasket.add("Молоко", 40,1,50);
        mashaBasket.add("Хлеб", 80,1,3);
        mashaBasket.print("Корзина Маши");
        System.out.println();

        Basket katyaBasket = new Basket("", 500);
        katyaBasket.add("Cтул", 200);
        katyaBasket.print("Корзина Кати");
        System.out.println(Basket.getTotalCount());
        System.out.println(Basket.getTotalCost());
    }
}

Ответы (1 шт):

Автор решения: Igor

Очень плохие названия переменных. В английском языке не хватает слов.

public class Basket {
  private static class AllBaskets {
    static int itemCount;
    static int cost;
  }
  ...
  public void add(String name, int price, int count) {
    ...
    AllBaskets.itemCount += count;
    AllBaskets.cost += price * count;
  }
  ...
  public static int getItemCountForAllBaskets() {
    return AllBaskets.itemCount;
  }
  public static int getCostForAllBaskets() {
    return AllBaskets.cost;
  }
}


    System.out.println(Basket.getItemCountForAllBaskets());
    System.out.println(Basket.getCostForAllBaskets());
→ Ссылка