1. 장바구니 기능 추가 (도전과제)
- 장바구니 생성 및 관리 기능
- 사용자가 선택한 상품을 장바구니에 추가할 수 있는 기능을 제공합니다.
- 장바구니는 상품명, 수량, 가격 정보를 저장하며, 항목을 동적으로 추가 및 조회할 수 있어야 합니다.
- 사용자가 잘못된 선택을 했을 경우 예외를 처리합니다(예: 유효하지 않은 상품 번호 입력)
- 재고 관리 시스템
- 상품을 장바구니에 담을 때 재고를 확인하고, 재고가 부족할 경우 경고 메시지를 출력합니다.
- 주문 완료 시 해당 상품의 재고를 차감합니다.
- 장바구니 출력 및 금액 계산
- 사용자가 주문을 시도하기 전에, 장바구니에 담긴 모든 상품과 총 금액을 출력합니다.
- 출력 예시
- 장바구니 담기 기능
- 상품을 선택하면 장바구니에 추가할 지 물어보고, 입력값에 따라 "추가", "취소" 처리합니다.
- 장바구니에 담은 목록을 출력합니다.
- 주문 기능
- 장바구니에 담긴 모든 항목을 출력합니다.
- 합산하여 총 금액을 계산하고, "주문하기"를 누르면 장바구니를 초기화하고 재고를 차감합니다.
2. 새로운 클래스
- 장바구니 기능을 구현하기 위해 새로운 클래스를 만들었다.
public class CartItem {
private Product product;
private int quantity;
private int price;
public CartItem(Product product, int quantity) {
this.product = product;
this.quantity = quantity;
this.price = product.getPrice();
}
public Product getProduct() {
return product;
}
public int getQuantity() {
return quantity;
}
public int getTotalPrice() {
return price * quantity;
}
}
public class Cart {
private List<CartItem> items;
public Cart(List<CartItem> items) {
this.items = items;
}
public List<CartItem> getItems() {
return items;
}
public void addItem(CartItem item) {
items.add(item);
}
public void removeItem(CartItem item) {}
public void displayCart() {
int index = 1;
for (CartItem item : items) {
Product product = item.getProduct();
System.out.println(index + "." + product.getName()
+ " | 단가: " + product.getPrice() + "원"
+ " | 수량: " + item.getQuantity() + "개");
index++;
}
}
}
- 장바구니 리스트와 장바구니에 담기는 아이템을 관리하는 클래스를 추가로 작성했다.
3. 기존 클래스의 변경
public class CommerceSystem implements Runnable {
private Cart cart;
@Override
public void run() {
Scanner scanner = new Scanner(System.in);
List<Category> categories = new ArrayList<>();
cart = new Cart(new ArrayList<>());
...
while (true) {
System.out.println("[ 실시간 커머스 플랫폼 메인 ]");
int index = 1;
for (Category category : categories) {
System.out.println(index + ". " + category.getCategoryName());
index++;
}
System.out.println("0. 종료 | 프로그램 종료");
System.out.println("[ 주문 관리 ]" + "\n"
+ "4. 장바구니 확인 | 장바구니를 확인 후 주문합니다."
+ "\n" + "5. 주문 취소 | 진행중인 주분을 취소합니다.");
int input = scanner.nextInt();
if (input == 0) {
System.out.println("커머스 플랫폼을 종료합니다.");
break;
}
if (input == 4) {
cart.displayCart();
System.out.println("1. 돌아가기");
int input3 = scanner.nextInt();
if (input3 == 1) {
continue;
}
}
...
try {
if (input >= 1 && input <= category.getProductCount()) {
Product selectedProduct = category.getProduct(input - 1);
category.displayProductDetail(input - 1);
System.out.println("위 상품을 장바구니에 추가하시겠습니까?" + "\n" + "1. 확인 " + " 2. 취소");
int input2 = scanner.nextInt();
switch(input2){
case 1:
System.out.print("수량을 입력하세요: ");
int quantity = scanner.nextInt();
if (quantity > 0) {
cart.addItem(new CartItem(selectedProduct, quantity));
System.out.println("장바구니에 추가되었습니다.");
} else {
System.out.println("수량은 1개 이상이어야 합니다.");
}
break;
case 2:
break;
default:
System.out.println("잘못된 입력 입니다.");
}
...
- 장바구니 기능에 맞춰 새로운 코드를 추가 및 수정하였다.
4. 마무리
- 장바구니를 확인하는 기능을 작성 중 처음에는 if (input3 == 1) { break; } 를 넣어서 작성했다. 이렇게 작성을 하니 메인 화면으로 돌아가는게 아니라 프로그램이 종료되었다. 현재 반복이 맨 첫번째 실행된 반복이다보니 break 를 쓰니 종료가 되버리는 것 이었다. continue 로 바꾸고 나니 건너뛰고 다시 처음으로 돌아오게 되었다.
- 아직 장바구니 기능의 모든것을 구현하지 못했다. 장바구니에서 주문으로 넘어가는 기능, 장바구니에 상품 가격의 총합을 보여주는 기능 등 구현하지 못한 기능들이 있으며 어떻게 구현해야 할지 고민이 많다.