spring_2기[본캠프]/과제

[과제] 커머스2-1 (필수기능 완료 + 도전레벨1)

minwoo95 2025. 12. 18. 22:09

Lv 1. 장바구니 및 주문하기 기능을 추가하기

  • [ ] 장바구니 생성 및 관리 기능
    • [ ] 사용자가 선택한 상품을 장바구니에 추가할 수 있는 기능을 제공합니다.
    • [ ] 장바구니는 상품명, 수량, 가격 정보를 저장하며, 항목을 동적으로 추가 및 조회할 수 있어야 합니다.
    • [ ] 사용자가 잘못된 선택을 했을 경우 예외를 처리합니다(예: 유효하지 않은 상품 번호 입력)
  • [ ] 재고 관리 시스템
    • [ ] 상품을 장바구니에 담을 때 재고를 확인하고, 재고가 부족할 경우 경고 메시지를 출력합니다.
    • [ ] 주문 완료 시 해당 상품의 재고를 차감합니다.
  • [ ] 장바구니 출력 및 금액 계산
    • [ ] 사용자가 주문을 시도하기 전에, 장바구니에 담긴 모든 상품과 총 금액을 출력합니다.
    • [ ] 출력 예시
      • [ ] 각 상품의 이름, 가격, 수량
      • [ ] 총 금액 합계
  • [ ] 장바구니 담기 기능
    • [ ] 상품을 선택하면 장바구니에 추가할 지 물어보고, 입력값에 따라 "추가", "취소" 처리합니다.
    • [ ] 장바구니에 담은 목록을 출력합니다.
  • [ ] 주문 기능
    • [ ] 장바구니에 담긴 모든 항목을 출력합니다.
    • [ ] 합산하여 총 금액을 계산하고, "주문하기"를 누르면 장바구니를 초기화하고 재고를 차감합니다.

Main

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

//TIP To <b>Run</b> code, press <shortcut actionId="Run"/> or
// click the <icon src="AllIcons.Actions.Execute"/> icon in the gutter.
public class Main {
    public static void main(String[] args) {
        //STEP 1. 객체 지향 설계를 적용해 상품 관리 시스템을 프로그래밍해보자
        //JAVA 프로그램을 실행하면 여러 전자제품을 출력, 제시된 상품 중 입력받은 숫자에 따라 다른 로직을 실행하는 코드를 작성합니다.
        //함수에서 Product 클래스를 생성하여 상품 목록을 추가합니다.
        //Product 객체 생성을 통해 상품명, 가격, 설명, 재고수량을 세팅합니다. [키워드: new]
        //Product클래스 생성자 (String productName, double productPrice, String productInformation, int productQuantity)
        Product GalaxyS25 = new Product("Galaxy S25",1200000,"최신 안드로이드 스마트폰",50);
        Product iPhone16 = new Product("iPhone 16",1350000,"Apple의 최신 스마트폰",0);
        Product MacBookPro = new Product("MacBook Pro",2400000,"M3 칩셋이 탑재된 노트북",20);
        Product AirPodsPro = new Product("AirPods Pro",350000,"노이즈 캔슬링 무선 이어폰",80);

        //List를 선언하여 여러 Product을 추가합니다. [List<Product> products = new ArrayList<>();]
        //CommerceSystem클래스로 이동
        List<Product> electronicsProducts = new ArrayList<>();
        electronicsProducts.add(GalaxyS25);
        electronicsProducts.add(iPhone16);
        electronicsProducts.add(MacBookPro);
        electronicsProducts.add(AirPodsPro);

        //반복문을 활용해 products를 탐색하면서 하나씩 접근합니다.
        //출력예시
        //        [ 실시간 커머스 플랫폼 - 전자제품 ]
//        1. Galaxy S25     | 1,200,000원 | 최신 안드로이드 스마트폰
//        2. iPhone 16      | 1,350,000원 | Apple의 최신 스마트폰
//        3. MacBook Pro    | 2,400,000원 | M3 칩셋이 탑재된 노트북
//        4. AirPods Pro    |   350,000원 | 노이즈 캔슬링 무선 이어폰
//        0. 종료           | 프로그램 종료
//        0 <- // 0을 입력
//
//                커머스 플랫폼을 종료합니다.
        //Product클래스 생성자 (String productName, double productPrice, String productInformation, int productQuantity)

//        System.out.println("        [ 실시간 커머스 플랫폼 - 전자제품 ]");
//        for (int index=0; index<products.size(); index++) {
//            int i = index+1;
//            System.out.println(i+"."+products.get(index));
//        }
//        System.out.println("0. 종료           | 프로그램 종료");//7칸 띄움

//        Scanner scanner = new Scanner(System.in);//입력을 받기위한 스캐너생성
//        String inputNum;//입력값 받는 변수
//        int passInputNum;
//        while (true) {
//            System.out.print("메뉴 번호를 입력 해주세요 :  ");
//            // Scanner를 사용하여 양의 정수를 입력받고 적합한 타입의 변수에 저장합니다.
//            //어떤 값이 입력될지 모르기때문에 String 타입으로 입력 받기
//            inputNum = scanner.nextLine();//입력 받기//첫번재 양의 정수를 입력받는다.
//            boolean condition = true;//입력값 검증상태를 저장하기 위해서
//
//            for (int i = 0; i < inputNum.length(); i++) {
//                char a = inputNum.charAt(i);//입력값 0번째부터 담아서 입력값을 1자리씩 검증하기 위한단계
//
//                if (a >= '0' && a <= '9') {
//                    continue;//입력값이 0부터 9사이 숫자면 통과
//                }else {
//                    condition = false;
//                    break;
//                }
//            }
//
//            if (condition == true) {
//                passInputNum = Integer.parseInt(inputNum);//검증이 끝난 문자열을 정수로 변환하여 변수에 저장
//                if(0< passInputNum && passInputNum <= products.size()) {
//                    Product product = products.get(passInputNum-1);
//                    System.out.println(product);
//                }else if(passInputNum == 0){
//                    System.out.println("         커머스 플랫폼을 종료합니다.");
//                    System.exit(0);
//                }else {//숫자이기는 하나 메뉴범위를 벗어난 번호인 경우
//                    System.out.println("0을 포함한 해당되는 메뉴의 번호만 입력하세요.(0~"+products.size()+")");
//                }
//            }else{//숫자가 아닌경우
//                System.out.println("0을 포함한 해당되는 메뉴의 번호만 입력하세요.(0~"+products.size()+")");
//            }
//        }

        //STEP 2. 객체 지향 설계를 적용해 순서 제어를 클래스로 관리하기
        //CommerceSystem 클래스 생성하기
        //설명: 커머스 플랫폼의 상품을 관리하고 사용자 입력을 처리하는 클래스입니다.
        //Product를 관리하는 리스트가 필드로 존재합니다.
        //main 함수에서 관리하던 입력과 반복문 로직은 이제 start 함수를 만들어 관리합니다.
        //List<Product> products 는 CommerceSystem 클래스 생성자를 통해 값을 할당합니다.
        //CommerceSystem 객체를 생성하고 사용하는 main 함수에서 객체를 생성할 때 값을 넘겨줍니다.
//        CommerceSystem commerceSystem = new CommerceSystem(products);//리스트 배열을 통째로 넘겨서 연결
//        commerceSystem.start();

        //STEP 3. 객체 지향 설계를 적용해 상품 카테고리와 고객 관리를 클래스 기반으로 관리하기
//        Category` 클래스 생성하기
//        설명 : Product 클래스를 관리하는 클래스입니다.
//        전자제품, 의류, 식품 등 각 카테고리 내에 여러 `Product`를 만들어 줍니다.
//        `List<Product>` 은 `CommerceSystem` 클래스가 관리하기에 적절하지 않으므로 Category 클래스가 관리하도록 변경합니다.
//        여러 상품들을 포함하는 상위 개념 '전자제품' 같은 `카테고리 이름` 필드를 갖습니다.
//        카테고리 이름을 반환하는 메서드가 구현되어야 합니다.
//        **`Customer` 클래스 생성하기**[완료]
//        설명 : 고객 정보를 관리하는 클래스입니다.
//        클래스는 `고객명`, `이메일`, `등급` 필드를 갖습니다.

        List<Category> category = new ArrayList<Category>();
        Category electronics = new Category("Electronics",electronicsProducts);
        category.add(electronics);
        //public Customer(String customerName, String customerEmail, String customerRating) 생성자 매개변수
        Customer  customer1 = new Customer("민우","minwoo@gmail.com");
        CommerceSystem commerceSystem = new CommerceSystem(category,customer1,"admin123");//리스트 배열을 통째로 넘겨서 연결
        commerceSystem.start();

        //**STEP 4**. 캡슐화 적용하기[이미 설계하면서 캡슐화를 셋팅하여 자동으로 완료]
        //`Product`, `Category`, `Customer` 그리고 `CommerceSystem` 클래스의 필드에 직접 접근하지 못하도록 설정합니다.
        //Getter와 Setter 메서드를 사용해 데이터를 관리합니다.

    }
}

 

Prouct

public class Product {
    //개별 상품 정보를 가지는 클래스
    //상품명, 가격, 설명, 재고수량
    //예시: Galaxy S24, 1200000, 최신 스마트폰, 50
    //new Product("Galaxy S24", 1200000, "최신 스마트폰", 50)

    //속성
    private String productName;
    private int productPrice;
    private String productInformation;
    private int productQuantity;

    //생성자
    public Product(String productName, int productPrice, String productInformation, int productQuantity) {
        this.productName = productName;
        this.productPrice = productPrice;
        this.productInformation = productInformation;
        this.productQuantity = productQuantity;
    }


    //기능
    //상품 수정(세터)
    public void setProductName(String productName) {
        this.productName=productName;
    }
    public void setproductPrice(int productPrice) {
        this.productPrice=productPrice;
    }
    public void setproductInformation(String productInformation) {
        this.productInformation=productInformation;
    }
    public int setproductQuantity() {
        this.productQuantity=this.productQuantity-1;
        return productQuantity;
    }
    //상품 정보 출력(게터)
    public String getProductName() {
        return productName;
    }
    public int getproductPrice() {
        return productPrice;
    }
    public String getproductInformation() {
        return productInformation;
    }
    public int setProductQuantity(int i) {
        this.productQuantity=productQuantity-i;
        return productQuantity;
    }
    public int getproductQuantity() {
        return productQuantity;
    }


    @Override
    public String toString() {//출력시 원하는 출력값을 위해서 출력 양식 설정
        // %,.0f: 천 단위 콤마 추가, 소수점은 표시 안 함
        // %-15s: 15자리를 확보하고 왼쪽 정렬 (글자 길이에 상관없이 줄 맞춤)
        return String.format("%-15s | %,10.0f원 | %s",productName, productPrice, productInformation);
    }
}

 

Category

import java.util.List;

public class Category {
    //Product 클래스를 관리하는 클래스
    //예시 : 전자제품, 의류, 식품 등 각 카테고리 내에 여러 Product를 포함합니다.

    //속성
    private List<Product> products;
    private String categoryName;

    //생성자
    public Category(String categoryName,List<Product> products) {
        this.products = products;
        this.categoryName = categoryName;
    }

    //기능
    public String getCategoryName() {
        return this.categoryName;
    }
    public Product getProductsItem(int i) {
        return this.products.get(i);
    }
    public List<Product> getProducts() {
        return this.products;
    }
}

 

Customer

import java.util.ArrayList;
import java.util.List;

public class Customer {
    //고객 정보를 관리하는 클래스
    //속성
    private String customerName;
    private String customerEmail;
    private String customerRating;//브론즈,실버,플레티넘,VIP 순서
    private List<Product> product =  new ArrayList<Product>();

    //생성자
    public Customer(String customerName, String customerEmail) {
        this.customerName = customerName;
        this.customerEmail = customerEmail;
        this.customerRating = "브론즈";//초기 등급은 브론즈
    }

    //기능
    public String getCustomerName() {
        return customerName;
    }
    public String getcustomerEmail() {
        return customerEmail;
    }
    public String getcustomerRating() {
        return customerRating;
    }

    public void addToCart(Product product) {
        this.product.add(product);
    }
    public List<Product> getProductList() {
        return product;
    }
    public Product getProduct(int id) {
        return product.get(id);
    }
    public double getProductTotalPrice() {
        double totalPrice = 0;
        for (Product product : product) {
            product.getproductPrice();
            totalPrice += product.getproductPrice();
        }
        return totalPrice;
    }
}

 

CommerceSystem

import java.util.*;

public class CommerceSystem {
    //프로그램 비즈니스 로직 클래스
    //설명: 커머스 플랫폼의 상품을 관리하고 사용자 입력을 처리하는 클래스입니다.[사용자 입력][상품 관리?]
    //Product를 관리하는 리스트가 필드로 존재합니다.[Product를 여기서 접근]
    //main 함수에서 관리하던 입력과 반복문 로직은 이제 start 함수를 만들어 관리합니다.[CommerceSystem.start()]
    //List<Product> products 는 CommerceSystem 클래스 생성자를 통해 값을 할당합니다.[main에서 생성한 List<Product> products를 CommerceSystem에 주입]
    //CommerceSystem 객체를 생성하고 사용하는 main 함수에서 객체를 생성할 때 값을 넘겨줍니다.[main에서 CommerceSystem접근 하여 Product를관리]


    //속성
    //products를 저장할 배열 선언->카테고리가 상품을 관리로 변경
    private List<Category> category;//묶어진 상자 배열을 담는 배열
    private List<Product> products;//같은 카테고리의 상품을 묶는 배열
    Product product;//선택한 상품이 담긴 변수
    Customer  customer;//고객정보 및 장바구니 담기위해서
    private String ADMIN_PASSWORD;
    private boolean loggedIn = false;

    //그외 필요한 클래스 변수 선언
    Scanner scanner = new Scanner(System.in);//입력을 받기위한 스캐너생성


    //생성자
    //3.main에서 주입받은 products 객체를 받아 배열에 저장
    public CommerceSystem(List<Category> category,Customer  customer,String ADMIN_PASSWORD){
        this.category = category;//받아온 리스트 배열을 통째로 List<Product>에 저장
        this.customer = customer;
        this.ADMIN_PASSWORD = ADMIN_PASSWORD;
    }

    //기능
    //1.Product 접근
    //2.입력과 로직을 반복하는 start
    public void start(){
        int categoryNumber = 0;
        while(true) {
            boolean isGobackStart = false;
            //어떤 카테고리를 선택할지? 정하는곳
            while (true) {
                //장바구니에 상품이 있는 경우
                if(!customer.getProductList().isEmpty()&&loggedIn==false){//장바구니가 비어있는지 확인
                    System.out.println("아래 메뉴를 선택해주세요.");
                    System.out.println("");

                    System.out.println("[ 실시간 커머스 플랫폼 메인 ]");
                    for (int i = 0; i < category.size(); i++) {
                        System.out.println((i + 1) + ". " + this.category.get(i).getCategoryName());
                    }
                    System.out.println("0. 종료      | 프로그램 종료");
                    System.out.println("");
                    System.out.println("[ 주문 관리 ]");
                    System.out.println("4. 장바구니 확인    | 장바구니를 확인 후 주문합니다.");
                    System.out.println("5. 주문 취소       | 진행중인 주문을 취소합니다.");

                }else if(loggedIn){//관리자 모드로 진입시
                    System.out.println("[ 관리자 모드 ]");
                    System.out.println("1. 상품 추가");
                    System.out.println("2. 상품 수정");
                    System.out.println("3. 상품 삭제");
                    System.out.println("4. 전체 상품 현황");
                    System.out.println("0. 메인으로 돌아가기");
                    System.out.println("");
                    break;
                }else{//장바구니에 상품이 없는경우(최초실행시)
                    System.out.println("");
                    System.out.println("[ 실시간 커머스 플랫폼 메인 ]");
                    for (int i = 0; i < category.size(); i++) {
                        System.out.println((i + 1) + ". " + this.category.get(i).getCategoryName());
                    }
                    System.out.println("0. 종료      | 프로그램 종료");
                    System.out.println("6. 관리자 모드");
                }

                String inputNum1;//입력값 받는 변수
                int passInputNum1;//검증이 끝난 입력값 저장 변수

                System.out.print("메뉴 번호를 입력 해주세요 :  ");
                // Scanner를 사용하여 양의 정수를 입력받고 적합한 타입의 변수에 저장합니다.
                //어떤 값이 입력될지 모르기때문에 String 타입으로 입력 받기
                inputNum1 = scanner.nextLine();//입력 받기//첫번재 양의 정수를 입력받는다.
                boolean condition = true;//입력값 검증상태를 저장하기 위해서
                System.out.println("");

                for (int i = 0; i < inputNum1.length(); i++) {
                    char a = inputNum1.charAt(i);//입력값 0번째부터 담아서 입력값을 1자리씩 검증하기 위한단계

                    if (a >= '0' && a <= '9') {
                        continue;//입력값이 0부터 9사이 숫자면 통과
                    } else {
                        condition = false;
                        break;
                    }
                }

                if (condition == true) {
                    passInputNum1 = Integer.parseInt(inputNum1);//검증이 끝난 문자열을 정수로 변환하여 변수에 저장
                    if (0 < passInputNum1 && passInputNum1 <= this.category.size()) {//카테고리 범위안에 숫자가 맞는지 검증
                        categoryNumber = passInputNum1;//통과한 입력값을 넘기기 위해 categoryNumber 저장
                        break;
                    } else if (passInputNum1 == 0) {
                        System.out.println("커머스 플랫폼을 종료합니다.");
                        System.exit(0);
                    }else if (!customer.getProductList().isEmpty()&&passInputNum1 == 4) {//장바구니에 상품이 있을때만 활성화 그외는 오입력처리
                        System.out.println("");
                        System.out.println("아래와 같이 주문 하시겠습니까?");
                        System.out.println("");
                        System.out.println("[ 장바구니 내역 ]");
                        Set<Product> distinctProducts = new HashSet<>(this.customer.getProductList());
                        for(Product p : distinctProducts){//장바구니 상품 출력
                            int productCount = Collections.frequency(this.customer.getProductList(), p);
                            System.out.printf("%s | %,.0f원 | %s | 수량: %d개%n", p.getProductName(), p.getproductPrice(), p.getproductInformation(), productCount);//출력하기
                        }
                        System.out.println("");
                        System.out.println("[ 총 주문 금액 ]");
                        System.out.printf("%,.0f원", this.customer.getProductTotalPrice());//총금액 출력하기
                        System.out.println("");
                        System.out.println("1. 주문 확정      2. 메인으로 돌아가기");
                        System.out.print("메뉴 번호를 입력 해주세요 :  ");
                        while (true) {
                            String inputNum5 = scanner.nextLine();//입력 받기//첫번재 양의 정수를 입력받는다.
                            boolean condition5 = true;//입력값 검증상태를 저장하기 위해서
                            System.out.println("");
                            System.out.println("");

                            for (int i = 0; i < inputNum5.length(); i++) {
                                char a = inputNum5.charAt(i);//입력값 0번째부터 담아서 입력값을 1자리씩 검증하기 위한단계

                                if (a >= '0' && a <= '9') {
                                    continue;//입력값이 0부터 9사이 숫자면 통과
                                } else {
                                    condition5 = false;
                                    break;
                                }
                            }
                            if (condition5 == true) {
                                int passInputNum5 = Integer.parseInt(inputNum5);//검증이 끝난 문자열을 정수로 변환하여 변수에 저장
                                if (0 < passInputNum5 && passInputNum5 <= 2) {//카테고리 범위안에 숫자가 맞는지 검증
                                    if(passInputNum5 == 2){
                                        break;
                                    }else if(passInputNum5 == 1){
                                        System.out.print("주문이 완료되었습니다! 총 금액: ");
                                        System.out.printf("%,.0f원", this.customer.getProductTotalPrice());//총금액 출력하기
                                        System.out.println("");
                                        for(Product p : this.customer.getProductList()){
                                            int oldQuantity = p.getproductQuantity();
                                            int newQuantity = p.setProductQuantity(1);
                                            System.out.printf("%s의 재고가 %d개에서 -> %d개로 업데이트 되었습니다.%n",p.getProductName(),oldQuantity,newQuantity);//출력하기
                                        }
                                        this.customer.getProductList().clear();//장바구니 초기화
                                        break;
                                    }
                                }
                            }else{
                                System.out.println("1과 2 둘중 하나의 번호만 입력해주세요.");
                            }
                        }
                    }else if(!customer.getProductList().isEmpty()&&passInputNum1 == 5){//장바구니에 상품이 있을때만 활성화 그외는 오입력처리
                        System.out.println("장바구니를 비우고 주문을 취소하겠습니다");
                        this.customer.getProductList().clear();
                        System.out.println("장바구니가 초기화되었습니다.");
                    }else if(passInputNum1 == 6){
                        System.out.println("관리자 비밀번호를 입력해주세요:");
                        String inputNum6 = scanner.nextLine();
                        if(inputNum6.equals(this.ADMIN_PASSWORD)){
                            System.out.println("정상 로그인 되었습니다.");
                            isGobackStart = true;
                            loggedIn = true;
                            break;
                        }else{
                            System.out.println("패스워드를 잘못입력 하셨습니다.");
                            isGobackStart = true;
                            break;
                        }
                    }else{//숫자이기는 하나 메뉴범위를 벗어난 번호인 경우
                        System.out.println("0을 포함한 해당되는 메뉴의 번호만 입력하세요.(0~" + this.category.size() + ")");
                        System.out.println("");
                    }
                } else {//숫자가 아닌경우
                    if(!this.customer.getProductList().isEmpty()){
                        System.out.println("0,4,5을 포함한 해당되는 메뉴의 번호만 입력하세요.(0~" + this.category.size() +")");
                        System.out.println("");
                    }else{
                        System.out.println("0을 포함한 해당되는 메뉴의 번호만 입력하세요.(0~" + this.category.size() + ")");
                        System.out.println("");
                    }

                }
            }
            while(true){//관리자 모드 진입시 처리 로직
                String inputNum6 = scanner.nextLine();//입력 받기//첫번재 양의 정수를 입력받는다.
                boolean condition6 = true;//입력값 검증상태를 저장하기 위해서
                for (int i = 0; i < inputNum6.length(); i++) {
                    char a = inputNum6.charAt(i);//입력값 0번째부터 담아서 입력값을 1자리씩 검증하기 위한단계

                    if (a >= '0' && a <= '9') {
                        continue;//입력값이 0부터 9사이 숫자면 통과
                    } else {//그외 조건은 거짓조건으로 오류문 출력
                        condition6 = false;
                        break;
                    }
                }
                if (condition6 == true) {
                    int passInputNum6 = Integer.parseInt(inputNum6);//검증이 끝난 문자열을 정수로 변환하여 변수에 저장
                    if (0 <= passInputNum6 && passInputNum6 <= 4) {//카테고리 범위안에 숫자가 맞는지 검증
                        if(passInputNum6 == 0){//메인으로 돌아가기
                            isGobackStart =  true;
                            break;
                        }else if(passInputNum6 == 1){//입력 검증 및 상품 추가 로직 구현
                            System.out.println("어느 카테고리에 상품을 추가하시겠습니까?");
                            System.out.println("1. 전자제품");
                            System.out.println("2. 의류");
                            System.out.println("3. 식품");
                            String inputNum7 = scanner.nextLine();//입력 받기//첫번재 양의 정수를 입력받는다.
                            boolean condition7 = true;//입력값 검증상태를 저장하기 위해서
                            for (int i = 0; i < inputNum7.length(); i++) {
                                char a = inputNum7.charAt(i);//입력값 0번째부터 담아서 입력값을 1자리씩 검증하기 위한단계

                                if (a >= '0' && a <= '9') {
                                    continue;//입력값이 0부터 9사이 숫자면 통과
                                } else {//그외 조건은 거짓조건으로 오류문 출력
                                    condition7 = false;
                                    break;
                                }
                            }
                            if (condition7 == true) {
                                if (passInputNum6 == 1) {
                                    System.out.println("[ 전자제품 카테고리에 상품 추가 ]");
                                    System.out.print("상품명을 입력해주세요:");
                                    String productName = scanner.nextLine();
                                    int passProductPrice = 0;
                                    int passProductQuantity = 0;
                                    while (true) {
                                        System.out.print("가격을 입력해주세요:");
                                        String productPrice = scanner.nextLine();
                                        boolean condition8 = true;//가격 검증상태를 저장하기 위해서
                                        for (int i = 0; i < productPrice.length(); i++) {
                                            char a = productPrice.charAt(i);//입력값 0번째부터 담아서 입력값을 1자리씩 검증하기 위한단계
                                            if (a >= '0' && a <= '9') {
                                                continue;//입력값이 0부터 9사이 숫자면 통과
                                            } else {//그외 조건은 거짓조건으로 오류문 출력
                                                condition8 = false;
                                                break;
                                            }
                                        }
                                        if (condition8 == true) {
                                            passProductPrice = Integer.parseInt(productPrice);//검증이 끝난 문자열을 정수로 변환하여 변수에 저장
                                            break;
                                        } else {
                                            System.out.println("상품의 가격을 양의 정수로 입력해주세요.");
                                        }
                                    }
                                    System.out.print("상품 설명을 입력해주세요:");
                                    String productInfomation = scanner.nextLine();
                                    while (true) {
                                        System.out.print("재고수량을 입력해주세요:");
                                        String productQuantity = scanner.nextLine();
                                        boolean condition8 = true;//가격 검증상태를 저장하기 위해서
                                        for (int i = 0; i < productQuantity.length(); i++) {
                                            char a = productQuantity.charAt(i);//입력값 0번째부터 담아서 입력값을 1자리씩 검증하기 위한단계

                                            if (a >= '0' && a <= '9') {
                                                continue;//입력값이 0부터 9사이 숫자면 통과
                                            } else {//그외 조건은 거짓조건으로 오류문 출력
                                                condition8 = false;
                                                break;
                                            }
                                        }
                                        if (condition8 == true) {
                                            passProductQuantity = Integer.parseInt(productQuantity);//검증이 끝난 문자열을 정수로 변환하여 변수에 저장
                                            break;
                                        } else {
                                            System.out.println("상품의 재고를 양의 정수로 입력해주세요.");
                                        }
                                    }
                                    while (true) {//상품 추가 입력 검증및 로직 구현
                                        System.out.printf("%s | %,.0f원 | %s | 수량: %d개%n", productName, passProductPrice, productInfomation, passProductQuantity);//출력하기
                                        System.out.println("위 정보로 상품을 추가하시겠습니까?");
                                        System.out.println("1. 확인    2. 취소");
                                        System.out.println("");

                                        String initNum = scanner.nextLine();
                                        boolean condition8 = true;//가격 검증상태를 저장하기 위해서
                                        for (int i = 0; i < initNum.length(); i++) {
                                            char a = initNum.charAt(i);//입력값 0번째부터 담아서 입력값을 1자리씩 검증하기 위한단계

                                            if (a >= '0' && a <= '9') {
                                                continue;//입력값이 0부터 9사이 숫자면 통과
                                            } else {//그외 조건은 거짓조건으로 오류문 출력
                                                condition8 = false;
                                                break;
                                            }
                                        }
                                        if (condition8 == true) {
                                            Category selectedCategory = this.category.get(passInputNum6);
                                            int passInputNum2 = Integer.parseInt(initNum);
                                            if (passInputNum2 == 1) {
                                                boolean isDuplicate = false;
                                                for (Category c : this.category) {
                                                    for(Product p : c.getProducts()) {
                                                        if(p.getProductName().equals(productName)) {
                                                            isDuplicate = true;
                                                            break;
                                                        }
                                                    }
                                                }
                                                if (isDuplicate) {
                                                    System.out.println("이미 존재하는 상품명입니다.");
                                                    break;
                                                } else {
                                                    // Product 객체 생성 (생성자에 인자 전달)
                                                    Product newProduct = new Product(productName, passProductPrice, productInfomation, passProductQuantity);

                                                    // 해당 카테고리 리스트에 추가
                                                    selectedCategory.getProducts().add(newProduct);
                                                    System.out.println("상품이 성공적으로 추가되었습니다!");
                                                    isGobackStart = true;
                                                }
                                            }else if(passInputNum2 == 2){
                                                System.out.println("상품 추가를 취소하고 돌아갑니다.");
                                                System.out.println("");
                                                isGobackStart = true;
                                            }
                                        } else {
                                            System.out.println("상품의 재고를 양의 정수로 입력해주세요.");
                                        }
                                    }
                                }
                            }
                        }else if(passInputNum6 == 2){
                            System.out.println("");
                            System.out.print("수정할 상품명을 입력해주세요:");

                        }
                    }
                }
            }
            if(isGobackStart){
                continue;
            }
            boolean isGoback= false;;
            //선택한 해당 카테고리의 상품목록을 불러오기
            while (true) {

                System.out.println("[ " + this.category.get(categoryNumber - 1).getCategoryName() + " 카테고리 ]");
                Category selectedCategory = this.category.get(categoryNumber - 1);//categoryNumber번째 카테고리 products 불러오기
                products = selectedCategory.getProducts();//불러온 해당 카테고리의 상품들을 products 객체에 담기
                for (int index = 0; index < products.size(); index++) {//해당 객체의 범위만큼만 돌도록 하기
                    int i = index + 1;
                    System.out.println(i + ". " + products.get(index));//반복문을 통해 리스트 출력
                }
                System.out.println("0. 뒤로가기");

                String inputNum2;//입력값 받는 변수
                int passInputNum;//검증이 끝난 입력값 저장 변수

                System.out.print("상품 또는 메뉴 번호를 입력 해주세요 :  ");
                // Scanner를 사용하여 양의 정수를 입력받고 적합한 타입의 변수에 저장합니다.
                //어떤 값이 입력될지 모르기때문에 String 타입으로 입력 받기
                inputNum2 = scanner.nextLine();//입력 받기//첫번재 양의 정수를 입력받는다.
                boolean condition = true;//입력값 검증상태를 저장하기 위해서

                for (int i = 0; i < inputNum2.length(); i++) {
                    char a = inputNum2.charAt(i);//입력값 0번째부터 담아서 입력값을 1자리씩 검증하기 위한단계

                    if (a >= '0' && a <= '9') {
                        continue;//입력값이 0부터 9사이 숫자면 통과
                    } else {
                        condition = false;
                        break;
                    }
                }

                if (condition == true) {
                    passInputNum = Integer.parseInt(inputNum2);//검증이 끝난 문자열을 정수로 변환하여 변수에 저장
                    if (0 < passInputNum && passInputNum <= products.size()) {//해당 products의 사이즈범위내 숫자를 입력받기
                        product = products.get(passInputNum - 1);//인덱스 값으로 접근하여 선택한 상품 꺼내기
                        System.out.print("선택한 상품: ");//출력하기
                        //[문제] toString 와 특정 상품의 별개로 원하는 정보를 출력하고 싶었으나, print나 println을 안됨
                        //[해결]printf를 사용하여 해결
                        System.out.printf("%s | %,.0f원 | %s | 재고: %d개%n", product.getProductName(), product.getproductPrice(), product.getproductInformation(), product.getproductQuantity());//출력하기
                        System.out.println("");
                        System.out.println("");
                        break;
                    } else if (passInputNum == 0) {//0이면 뒤로가기
                        isGoback = true;
                        break;
                    } else {//숫자이기는 하나 메뉴범위를 벗어난 번호인 경우
                        System.out.println("0을 포함한 해당되는 메뉴의 번호만 입력하세요.(0~" + products.size() + ")");
                        System.out.println("");
                    }
                } else {//숫자가 아닌경우
                    System.out.println("0을 포함한 해당되는 메뉴의 번호만 입력하세요.(0~" + products.size() + ")");
                    System.out.println("");
                }
            }
            if(isGoback == true){
                continue;
            }
            while (true) {
                String inputNum3;//입력값 받는 변수
                int passInputNum3;//검증이 끝난 입력값 저장 변수
                System.out.printf("\"%s | %,.0f원 | %s\"", product.getProductName(), product.getproductPrice(), product.getproductInformation());//출력하기
                System.out.println("위 상품을 장바구니에 추가하시겠습니까?");
                System.out.println("1. 확인        2. 취소");
                System.out.print("답변을 입력해주세요 :  ");
                // Scanner를 사용하여 양의 정수를 입력받고 적합한 타입의 변수에 저장합니다.
                //어떤 값이 입력될지 모르기때문에 String 타입으로 입력 받기
                inputNum3 = scanner.nextLine();//입력 받기//첫번재 양의 정수를 입력받는다.
                boolean condition3 = true;//입력값 검증상태를 저장하기 위해서
                System.out.println("");
                System.out.println("");

                for (int i = 0; i < inputNum3.length(); i++) {
                    char a = inputNum3.charAt(i);//입력값 0번째부터 담아서 입력값을 1자리씩 검증하기 위한단계

                    if (a >= '0' && a <= '9') {
                        continue;//입력값이 0부터 9사이 숫자면 통과
                    } else {
                        condition3 = false;
                        break;
                    }
                }
                if (condition3 == true) {
                    passInputNum3 = Integer.parseInt(inputNum3);//검증이 끝난 문자열을 정수로 변환하여 변수에 저장
                    if(passInputNum3 == 1) {//1번 입력시 장바구니에 추가 하였다고 출력
                        if(product.getproductQuantity() <= 0){
                            System.out.printf("%s의 재고가 부족합니다.",product.getProductName());
                            System.out.println("");
                            break;
                        }
                        customer.addToCart(product);//주문상품을 고객클래스에 저장
                        System.out.printf("%s",product.getProductName());
                        System.out.print("가 장바구니에 추가되었습니다.");
                        System.out.println("");
                        System.out.println("");
                        System.out.println("");
                        break;
                    }else if(passInputNum3 == 2){//2이면 뒤로가기
                        break;
                    }else {//숫자이기는 하나 메뉴범위를 벗어난 번호인 경우
                        System.out.println("1과 2 둘중 하나의 번호만 입력해주세요.");
                        System.out.println("");
                    }
                }else{//숫자가 아닌경우
                    System.out.println("1과 2 둘중 하나의 번호만 입력해주세요.");
                    System.out.println("");
                }
            }
        }
    }
}

 

 

 

도전과제 레벨2를 작성중이다....

침착하게 레벨3까지 잘 완주 할수 있기를...