본문 바로가기

JavaCode(review)

collections challenge 종합

반응형

참고)

default V getOrDefault(Object key, V defaultValue)

찾는 키가 존재한다면 찾는 키의 값을 반환하고 없다면 기본 값을 반환한다.

int inBasket = list.getOrDefault(item, 0);

 

 

Main Class- StockList Class - StockItem Class - Basket Class

                 (hashMap)                                   (treeMap)

 

>HashMap-> for문만 이용 출력 or for-Entry 이용 출력

>ternary operation (boolean ? true : false) 이용  // 

  예) 사이즈가 1이면 "item", 아니면 "items"
String s = ((list.size() == 1) ? " item" : " items") + "\n";

package com.timbuchalka;

import java.util.Map;

public class Main {
//stockList object
    private static StockList stockList = new StockList();

    public static void main(String[] args) {
//stockItem object // call constructor = setter
	    StockItem temp = new StockItem("bread", 0.86, 100);
        stockList.addStock(temp);  // -> stockList에 stockItem add (addmethod이용)

        temp = new StockItem("cake", 1.10, 7);
        stockList.addStock(temp);

        temp = new StockItem("car", 12.50, 2);
        stockList.addStock(temp);

        temp = new StockItem("chair", 62.0, 10);
        stockList.addStock(temp);

        temp = new StockItem("cup", 0.50, 200);
        stockList.addStock(temp);
        temp = new StockItem("cup", 0.45, 7);
        stockList.addStock(temp);

        temp = new StockItem("door", 72.95, 4);
        stockList.addStock(temp);

        temp = new StockItem("juice", 2.50, 36);
        stockList.addStock(temp);

        temp = new StockItem("phone", 96.99, 35);
        stockList.addStock(temp);

        temp = new StockItem("towel", 2.40, 80);
        stockList.addStock(temp);

        temp = new StockItem("vase", 8.76, 40);
        stockList.addStock(temp);

        System.out.println(stockList);
//stocklist에 item추가 끝! -> 출력

        for(String s: stockList.Items().keySet()) { // for문 이용 key값만 출력.
            System.out.println(s);
        }
    // Map.Entry 이용하여 key값만 출력하는 코딩 (결과 동일)
    //        for(Map.Entry m :stockList.Items().entrySet()){
    //            System.out.println(m.getKey() );
    //
    //        }

//Basket object // call constructor = setter
        Basket timsBasket = new Basket("Tim");

//main method sell
        sellItem(timsBasket, "car", 1);
        System.out.println(timsBasket);

        sellItem(timsBasket, "car", 1);
        System.out.println(timsBasket);

        if(sellItem(timsBasket, "car", 1) != 1) {
            System.out.println("There are no more cars in stock");
        }

        sellItem(timsBasket, "spanner", 5);
//        System.out.println(timsBasket);

        sellItem(timsBasket, "juice", 4);
        sellItem(timsBasket, "cup", 12);
        sellItem(timsBasket, "bread", 1);
//        System.out.println(timsBasket);

//        System.out.println(stockList);

        Basket basket = new Basket("customer");
        sellItem(basket, "cup", 100);
        sellItem(basket, "juice", 5);
        removeItem(basket, "cup", 1);
        System.out.println(basket);

        removeItem(timsBasket, "car", 1);
        removeItem(timsBasket, "cup", 9);
        removeItem(timsBasket, "car", 1);
        System.out.println("cars removed: " + removeItem(timsBasket, "car", 1));  // should not remove any

        System.out.println(timsBasket);

        // remove all items from timsBasket
        removeItem(timsBasket, "bread", 1);
        removeItem(timsBasket, "cup", 3);
        removeItem(timsBasket, "juice", 4);
        removeItem(timsBasket, "cup", 3);
        System.out.println(timsBasket);

        System.out.println("\nDisplay stock list before and after checkout");
        System.out.println(basket);
        System.out.println(stockList);
        checkOut(basket);
        System.out.println(basket);
        System.out.println(stockList);

//        temp = new StockItem("pen", 1.12);
//        stockList.Items().put(temp.getName(), temp);
        StockItem car = stockList.Items().get("car");
        if(car != null) {
            car.adjustStock(2000);
        }
        if(car != null) {
            stockList.get("car").adjustStock(-1000);
        }

        System.out.println(stockList);
//        for(Map.Entry<String, Double> price: stockList.PriceList().entrySet()) {
//            System.out.println(price.getKey() + " costs " + price.getValue());
//        }

        checkOut(timsBasket);
        System.out.println(timsBasket);


    }

    public static int sellItem(Basket basket, String item, int quantity) {
        // retrieve the item from stock list
        StockItem stockItem = stockList.get(item);
        if(stockItem == null) {
            System.out.println("We don't sell " + item);
            return 0;
        }
        if(stockList.reserveStock(item, quantity) != 0) {
            return basket.addToBasket(stockItem, quantity);
        }
        return 0;
    }

    public static int removeItem(Basket basket, String item, int quantity) {
        // retrieve the item from stock list
        StockItem stockItem = stockList.get(item);
        if(stockItem == null) {
            System.out.println("We don't sell " + item);
            return 0;
        }
        if(basket.removeFromBasket(stockItem, quantity) == quantity) {
            return stockList.unreserveStock(item, quantity);
        }
        return 0;
    }

    public static void checkOut(Basket basket) {
        for (Map.Entry<StockItem, Integer> item : basket.Items().entrySet()) {
            stockList.sellStock(item.getKey().getName(), item.getValue());
        }
        basket.clearBasket();
    }

}



// Stocklist Class
package com.timbuchalka;

import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * Created by dev on 16/02/2016.
 */
public class StockList {
    private final Map<String, StockItem> list;      //list define

    public StockList() {
        this.list = new LinkedHashMap<>();      //linkedHashMap : 입력순(key,value):검색용이
    }

    public int addStock(StockItem item) {
        if(item != null) {
            // check if already have quantities of this item
            StockItem inStock = list.getOrDefault(item.getName(), item);
            // If there are already stocks on this item, adjust the quantity
            if(inStock != item) {
                item.adjustStock(inStock.availableQuantity());
            }

            list.put(item.getName(), item);
            return item.availableQuantity();
        }
        return 0;
    }

    public int sellStock(String item, int quantity) {
        StockItem inStock = list.get(item);

        if((inStock != null) && (quantity > 0)) {
            return inStock.finaliseStock(quantity);
        }
        return 0;
//        StockItem inStock = list.getOrDefault(item, null);
//
//        if((inStock != null) && (inStock.availableQuantity() >= quantity) && (quantity >0)) {
//            inStock.adjustStock(-quantity);
//            return quantity;
//        }
//        return 0;
    }

    public int reserveStock(String item, int quantity) {
        StockItem inStock = list.get(item);

        if((inStock != null) && (quantity > 0)) {
            return inStock.reserveStock(quantity);
        }
        return 0;
    }

    public int unreserveStock(String item, int quantity) {
        StockItem inStock = list.get(item);

        if((inStock != null) && (quantity > 0)) {
            return inStock.unreserveStock(quantity);
        }
        return 0;

    }

    public StockItem get(String key) {
        return list.get(key);
    }

    public Map<String, Double> PriceList() {
        Map<String, Double> prices = new LinkedHashMap<>();
        for(Map.Entry<String, StockItem> item : list.entrySet()) {
            prices.put(item.getKey(), item.getValue().getPrice());
        }
        return Collections.unmodifiableMap(prices);
    }

    public Map<String, StockItem> Items() {
        return Collections.unmodifiableMap(list);
    }

    @Override
    public String toString() {
        String s = "\nStock List\n";
        double totalCost = 0.0;
        for (Map.Entry<String, StockItem> item : list.entrySet()) {
            StockItem stockItem = item.getValue();

            double itemValue = stockItem.getPrice() * stockItem.availableQuantity();

            s = s + stockItem + ". There are " + stockItem.availableQuantity() + " in stock. Value of items: ";
            s = s + String.format("%.2f",itemValue) + "\n";
            totalCost += itemValue;
        }

        return s + "Total stock value " + totalCost;
    }
}



//StockItem Class
package com.timbuchalka;

/**
 * Created by dev on 16/02/2016.
 */
public class StockItem implements Comparable<StockItem> {
    private final String name;
    private double price;
    private int quantityInStock = 0;
    private int reserved = 0;

    //call constructor
    public StockItem(String name, double price) {
        this.name = name;
        this.price = price;
        this.quantityInStock = 0;  // or here (but you wouldn't normally do both).
    }

    //call constructor
    public StockItem(String name, double price, int quantityInStock) {
        this.name = name;
        this.price = price;
        this.quantityInStock = quantityInStock;
    }

    public String getName() {
        return name;
    }

    public double getPrice() {
        return price;
    }

    public int availableQuantity() {
        return quantityInStock - reserved;
    }

    public void setPrice(double price) {
        if(price > 0.0) {
            this.price = price;
        }
    }

    public void adjustStock(int quantity) {
        int newQuantity = this.quantityInStock + quantity;
        if(newQuantity >=0) {
            this.quantityInStock = newQuantity;
        }
    }

    public int reserveStock(int quantity) {
        if (quantity <= availableQuantity()) {
            reserved += quantity;
            return quantity;
        }
        return 0;
    }

    public int unreserveStock(int quantity) {
        if(quantity <= reserved) {
            reserved -= quantity;
            return quantity;
        }
        return 0;
    }

    public int finaliseStock(int quantity) {
        if (quantity <= reserved) {
            quantityInStock -= quantity;
            reserved -= quantity;
            return quantity;
        }

        return 0;
    }

    @Override
    public boolean equals(Object obj) {
        System.out.println("Entering StockItem.equals");
        if(obj == this) {
            return true;
        }

        if((obj == null) || (obj.getClass() != this.getClass())) {
            return false;
        }

        String objName = ((StockItem) obj).getName();
        return this.name.equals(objName);
    }

    @Override
    public int hashCode() {
        return this.name.hashCode() + 31;
    }

    @Override
    public int compareTo(StockItem o) {
//        System.out.println("Entering StockItem.compareTo");
        if(this == o) {
            return 0;
        }

        if(o != null) {
            return this.name.compareTo(o.getName());
        }

        throw new NullPointerException();
    }

    //Output
    @Override
    public String toString() {
        return this.name + " : price " + this.price + ". Reserved: " + this.reserved;
    }
}



// Basket Class
package com.timbuchalka;

import java.util.Collections;
import java.util.Map;
import java.util.TreeMap;

/**
 * Created by dev on 17/02/2016.
 */
public class Basket {
    private final String name;
    private final Map<StockItem, Integer> list;

    public Basket(String name) {
        this.name = name;
        this.list = new TreeMap<>();
    }

    public int addToBasket(StockItem item, int quantity) {
        if ((item != null) && (quantity > 0)) {
            int inBasket = list.getOrDefault(item, 0);
            list.put(item, inBasket + quantity);
            return inBasket;
        }
        return 0;
    }

    public int removeFromBasket(StockItem item, int quantity) {
        if((item != null) && (quantity > 0)) {
            // check if we already have the item in the basket
            int inBasket = list.getOrDefault(item, 0);
            int newQuantity = inBasket - quantity;

            if(newQuantity > 0) {
                list.put(item, newQuantity);
                return quantity;
            } else if(newQuantity == 0) {
                list.remove(item);
                return quantity;
            }
        }
        return 0;
    }

    public void clearBasket() {
        this.list.clear();
    }

    public Map<StockItem, Integer> Items() {
        return Collections.unmodifiableMap(list);
    }

    //Output
    @Override
    public String toString() {                                                  //사이즈가 1이면 "item", 아니면 "items"
        String s = "\nShopping basket " + name + " contains " + list.size() + ((list.size() == 1) ? " item" : " items") + "\n";
        double totalCost = 0.0;
        for (Map.Entry<StockItem, Integer> item : list.entrySet()) {
            s = s + item.getKey() + ". " + item.getValue() + " purchased\n";
            totalCost += item.getKey().getPrice() * item.getValue();
        }
        return s + "Total cost " + totalCost;
    }
}



//Output
D:\IT\JDK\jdk11.0.6_10\bin\java.exe "-javaagent:D:\IT\IDEA\IntelliJ IDEA Community Edition 2020.1\lib\idea_rt.jar=51271:D:\IT\IDEA\IntelliJ IDEA Community Edition 2020.1\bin" -Dfile.encoding=UTF-8 -classpath "D:\IT\Java-Collections-Challenge-Part-4-(Final)-Source-code\out\production\sortedCollections" com.timbuchalka.Main

Stock List
bread : price 0.86. Reserved: 0. There are 100 in stock. Value of items: 86.00
cake : price 1.1. Reserved: 0. There are 7 in stock. Value of items: 7.70
car : price 12.5. Reserved: 0. There are 2 in stock. Value of items: 25.00
chair : price 62.0. Reserved: 0. There are 10 in stock. Value of items: 620.00
cup : price 0.45. Reserved: 0. There are 207 in stock. Value of items: 93.15
door : price 72.95. Reserved: 0. There are 4 in stock. Value of items: 291.80
juice : price 2.5. Reserved: 0. There are 36 in stock. Value of items: 90.00
phone : price 96.99. Reserved: 0. There are 35 in stock. Value of items: 3394.65
towel : price 2.4. Reserved: 0. There are 80 in stock. Value of items: 192.00
vase : price 8.76. Reserved: 0. There are 40 in stock. Value of items: 350.40
Total stock value 5150.699999999999
bread
cake
car
chair
cup
door
juice
phone
towel
vase

Shopping basket Tim contains 1 item
car : price 12.5. Reserved: 1. 1 purchased
Total cost 12.5

Shopping basket Tim contains 1 item
car : price 12.5. Reserved: 2. 2 purchased
Total cost 25.0
There are no more cars in stock
We don't sell spanner

Shopping basket customer contains 2 items
cup : price 0.45. Reserved: 111. 99 purchased
juice : price 2.5. Reserved: 9. 5 purchased
Total cost 57.050000000000004
cars removed: 0

Shopping basket Tim contains 3 items
bread : price 0.86. Reserved: 1. 1 purchased
cup : price 0.45. Reserved: 102. 3 purchased
juice : price 2.5. Reserved: 9. 4 purchased
Total cost 12.21

Shopping basket Tim contains 0 items
Total cost 0.0

Display stock list before and after checkout

Shopping basket customer contains 2 items
cup : price 0.45. Reserved: 99. 99 purchased
juice : price 2.5. Reserved: 5. 5 purchased
Total cost 57.050000000000004

Stock List
bread : price 0.86. Reserved: 0. There are 100 in stock. Value of items: 86.00
cake : price 1.1. Reserved: 0. There are 7 in stock. Value of items: 7.70
car : price 12.5. Reserved: 0. There are 2 in stock. Value of items: 25.00
chair : price 62.0. Reserved: 0. There are 10 in stock. Value of items: 620.00
cup : price 0.45. Reserved: 99. There are 108 in stock. Value of items: 48.60
door : price 72.95. Reserved: 0. There are 4 in stock. Value of items: 291.80
juice : price 2.5. Reserved: 5. There are 31 in stock. Value of items: 77.50
phone : price 96.99. Reserved: 0. There are 35 in stock. Value of items: 3394.65
towel : price 2.4. Reserved: 0. There are 80 in stock. Value of items: 192.00
vase : price 8.76. Reserved: 0. There are 40 in stock. Value of items: 350.40
Total stock value 5093.65

Shopping basket customer contains 0 items
Total cost 0.0

Stock List
bread : price 0.86. Reserved: 0. There are 100 in stock. Value of items: 86.00
cake : price 1.1. Reserved: 0. There are 7 in stock. Value of items: 7.70
car : price 12.5. Reserved: 0. There are 2 in stock. Value of items: 25.00
chair : price 62.0. Reserved: 0. There are 10 in stock. Value of items: 620.00
cup : price 0.45. Reserved: 0. There are 108 in stock. Value of items: 48.60
door : price 72.95. Reserved: 0. There are 4 in stock. Value of items: 291.80
juice : price 2.5. Reserved: 0. There are 31 in stock. Value of items: 77.50
phone : price 96.99. Reserved: 0. There are 35 in stock. Value of items: 3394.65
towel : price 2.4. Reserved: 0. There are 80 in stock. Value of items: 192.00
vase : price 8.76. Reserved: 0. There are 40 in stock. Value of items: 350.40
Total stock value 5093.65

Stock List
bread : price 0.86. Reserved: 0. There are 100 in stock. Value of items: 86.00
cake : price 1.1. Reserved: 0. There are 7 in stock. Value of items: 7.70
car : price 12.5. Reserved: 0. There are 1002 in stock. Value of items: 12525.00
chair : price 62.0. Reserved: 0. There are 10 in stock. Value of items: 620.00
cup : price 0.45. Reserved: 0. There are 108 in stock. Value of items: 48.60
door : price 72.95. Reserved: 0. There are 4 in stock. Value of items: 291.80
juice : price 2.5. Reserved: 0. There are 31 in stock. Value of items: 77.50
phone : price 96.99. Reserved: 0. There are 35 in stock. Value of items: 3394.65
towel : price 2.4. Reserved: 0. There are 80 in stock. Value of items: 192.00
vase : price 8.76. Reserved: 0. There are 40 in stock. Value of items: 350.40
Total stock value 17593.65

Shopping basket Tim contains 0 items
Total cost 0.0

Process finished with exit code 0