'한빛아카데미 - JAVA 마스터' 교재의 프로젝트 내용입니다.


프로젝트 구조도

 

PART14 윈도우 기반 온라인 서점 만들기

 

com.market.main 패키지

- Welcome 클래스 생성

package com.market.main;

public class Welcome {
	
	public static void main(String[] args) {
		new GuestWindow("고객 정보 입력", 0, 0, 1000, 750);
	}
}

 

com.market.main 패키지

- GuestWindow 클래스 수정

package com.market.main;

import javax.swing.*;
import java.awt.*;

import com.market.member.UserInIt;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class GuestWindow extends JFrame {
	
	public GuestWindow(String title, int x, int y, int width, int height) {
		initContainer(title, x, y, width, height); // initContainer() 메서드 호출
		setVisible(true); // 프레임 보이기 설정
		setResizable(true); // 프레임 크기 조절 가능 설정
		setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); // 프레임 닫기 버튼 가능 설정
		setIconImage(new ImageIcon("src/images/shop.png").getImage()); // 프레임 아이콘 표시 // ./images/shop.png 이미지 불러오지 못함
	}
	
	private void initContainer(String title, int x, int y, int width, int height) {
		setTitle(title); // 프레임 제목 설정
		setBounds(x, y, width, height); // 프레임 위치, 크기 설정
		setLayout(null); // 프레임 레이아웃 미설정
		
		Font ft;
		ft = new Font("함초롬돋움", Font.BOLD, 15); // 글꼴, 스타일, 크기 설정
		
		Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
		setLocation((screenSize.width - 1000) / 2, (screenSize.height - 750 ) / 2); // 컴퓨터 화면에 맞춰 프레임 창을 화면 중앙에 출력
		
		// user.png 이미지 표시를 위한 패널 영역 설정 및 출력
		JPanel userPanel = new JPanel();
		userPanel.setBounds(0, 100, 1000, 256);
		
		ImageIcon imageIcon = new ImageIcon("src/images/user.png");  // ./images/user.png 이미지 불러오지 못함
		imageIcon.setImage(imageIcon.getImage().getScaledInstance(160, 160, Image.SCALE_SMOOTH));
		JLabel userLabel = new JLabel(imageIcon);
		userPanel.add(userLabel);
		add(userPanel);
		
		// -- 고객 정보를 입력하세요 -- 표시를 위한 패널 영역 설정 및 출력
		
		JPanel titlePanel = new JPanel();
		titlePanel.setBounds(0, 350, 1000, 50);
		add(titlePanel);
		
		JLabel titleLabel = new JLabel("-- 고객 정보를 입력하세요 --");
		titleLabel.setFont(ft); // JLabel인 titleLabel 글꼴 설정
		titleLabel.setForeground(Color.BLUE); // JLabel인 titleLabel 문자열 색상 설정
		titlePanel.add(titleLabel);
		
		// 이름 표시를 위한 패널 영역 설정 및 출력
		JPanel namePanel = new JPanel();
		namePanel.setBounds(0, 400, 1000, 50);
		add(namePanel);
		
		JLabel nameLabel = new JLabel("이   름 : ");
		nameLabel.setFont(ft);
		namePanel.add(nameLabel);
		
		// 이름 표시를 위한 패널 영역 설정 및 출력
		JTextField nameField = new JTextField(10);
		nameField.setFont(ft);
		namePanel.add(nameField);
		
		// 연락처 표시를 위한 패널 영역 설정 및 출력
		JPanel phonePanel = new JPanel();
		phonePanel.setBounds(0, 450, 1000, 50);
		add(phonePanel);
		
		JLabel phoneLabel = new JLabel("연락처 : ");
		phonePanel.setFont(ft);
		phonePanel.add(phoneLabel);
		
		JTextField phoneField = new JTextField(10);
		phonePanel.setFont(ft);
		phonePanel.add(phoneField);
		
		// <쇼핑하기> 버튼 표시를 위한 패널 영역 설정 및 출력
		JPanel buttonPanel = new JPanel();
		buttonPanel.setBounds(0, 500, 1000, 100);
		add(buttonPanel);
		
		JLabel buttonLabel = new JLabel("쇼핑하기", new ImageIcon("src/images/shop.png"), JLabel.LEFT);   // images/shop.png 이미지 불러오지 못함
		buttonLabel.setFont(ft);
		JButton enterButton = new JButton();
		enterButton.add(buttonLabel);
		buttonPanel.add(enterButton);
		
		enterButton.addActionListener(new ActionListener() { // 쇼핑하기 버튼의 클릭 이벤트 처리
			public void actionPerformed(ActionEvent e) {
				
				JLabel message = new JLabel("고객 정보를 입력하세요");
				
				if(nameField.getText().isEmpty() || phoneField.getText().isEmpty()) // 이름 또는 연락처를 입력하지 않았을 때 오류 메시지 대화상자 표시
					JOptionPane.showMessageDialog(enterButton, message, "고객정보", JOptionPane.ERROR_MESSAGE);
				else { // 이름 또는 연락처를 입력했을 때 온라인 서점 프레임 생성 호출
					
					UserInIt.init(nameField.getText(), Integer.parseInt(phoneField.getText())); // 입력한 고객 정보 저장
					dispose(); // 대화상자 닫기
					new MainWindow("온라인 서점", 0, 0, 1000, 750);
					// MinWindow 프레임 호출
				}
			}
		});
	} 
	
}

 

- MainWindow 클래스 수정

package com.market.main;

import javax.swing.*;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import com.market.page.GuestInfoPage;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import com.market.cart.Cart;
import com.market.bookitem.BookInIt;
import com.market.page.CartAddItemPage;
import com.market.page.CartItemListPage;
import com.market.page.CartShippingPage;
import com.market.page.AdminLoginDialog;
import com.market.page.AdminPage;

public class MainWindow extends JFrame {
	static Cart mCart;
	static JPanel mMenuPanel, mPagePanel;
	
	public MainWindow(String title, int x, int y, int width, int height) {
		initContainer(title, x, y, width, height); // initContainer() 메서드 호출
		initMenu();
		setVisible(true); // 프레임 보이기 설정
		setResizable(true); // 프레임 크기 조절 가능 설정
		setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); // 프레임 닫기 버튼 가능 설정
		setIconImage(new ImageIcon("src/images/shop.png").getImage()); // 프레임 아이콘 표시 // ./images/shop.png 이미지 불러오지 못함
	}
	
	private void initContainer(String title, int x, int y, int width, int height) {
		setTitle(title);
		; // 프레임 제목 설정
		setBounds(x, y, width, height); // 프레임 위치, 크기 설정
		setLayout(null); // 프레임 레이아웃 미설정
		
		Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
		setLocation((screenSize.width - 1000) / 2, (screenSize.height - 750) / 2); // 컴퓨터 화면에 맞춰 프레임 창을 화면 중앙에 출력
		
		mMenuPanel = new JPanel();
		mMenuPanel.setBounds(0, 20, width, 130);
		menuIntroduction();
		add(mMenuPanel);
		
		mPagePanel = new JPanel();
		mPagePanel.setBounds(0, 150, width, height);
		add(mPagePanel);
		
		this.addWindowListener(new WindowAdapter() { // 프레임 닫기 버튼 클릭 이벤트 처리
			@Override
			public void windowClosed(WindowEvent e) {
				setVisible(false); // 현재 프레임 감추기
				new GuestWindow("고객 정보 입력", 0, 0, 1000, 750);
			}
		});
	}
	
	private void menuIntroduction() {
		mCart = new Cart();
		Font ft;
		ft = new Font("함초롬돋움", Font.BOLD, 15); // 글꼴, 스타일, 크기 설정
		
		JButton bt1 = new JButton("고객 정보 확인하기", new ImageIcon("src/images/1.png"));
		bt1.setBounds(0, 0, 100, 50);
		bt1.setFont(ft);
		mMenuPanel.add(bt1);
		
		// <고객 정보 확인하기> 버튼 표시를 위한 패널 영역 설정 및 출력
		bt1.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				mPagePanel.removeAll(); // 패널(mPagePanel)에 표시된 구성 요소 모두 삭제
				mPagePanel.add("고객 정보 확인", new GuestInfoPage(mPagePanel)); // 패널(mPagePanel)에 GuestInfoPage의 내용 출력
				mPagePanel.revalidate(); // 구성 요소 가로/세로 속성 변경하여 호출
				mPagePanel.repaint(); // 구성요소 모양을 변경하여 호출
			}
		});
		
		JButton bt2 = new JButton("장바구니 상품목록보기", new ImageIcon("src/images/2.png"));
		bt2.setBounds(0, 0, 100, 30);
		bt2.setFont(ft);
		mMenuPanel.add(bt2);
		
		// <장바구니 상품 목록보기> 버튼 표시를 위한 패널 영역 설정 및 출력
		bt2.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				
				if (mCart.mCartCount == 0)
					JOptionPane.showMessageDialog(bt2, "장바구니에 항목이 없습니다", "장바구니 상품 목록 보기", JOptionPane.ERROR_MESSAGE);
				else {
					mPagePanel.removeAll();
					mPagePanel.add("장바구니 상품 목록 보기", new CartItemListPage(mPagePanel, mCart));
					mPagePanel.revalidate();
					mPagePanel.repaint();
				}
			}
		});
		
		// <장바구니 비우기> 버튼 표시를 위한 패널 영역 설정 및 출력
		JButton bt3 = new JButton("장바구니 비우기", new ImageIcon("src/images/3.png"));
		bt3.setBounds(0, 0, 100, 30);
		bt3.setFont(ft);
		mMenuPanel.add(bt3);
		
		bt3.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				
				if (mCart.mCartCount == 0)
					JOptionPane.showMessageDialog(bt3, "장바구니에 항목이 없습니다", "장바구니 비우기", JOptionPane.ERROR_MESSAGE);
				else {
					mPagePanel.removeAll();
					menuCartClear(bt3);
					mPagePanel.add("장바구니 비우기", new CartItemListPage(mPagePanel, mCart));
					mPagePanel.revalidate();
					mPagePanel.repaint();
				}
			}
		});
		
		// <장바구니에 항목 추가하기> 버튼 표시를 위한 패널 영역 설정 및 출력
		JButton bt4 = new JButton("장바구니에 항목추가하기", new ImageIcon("src/images/4.png"));
		bt4.setFont(ft);
		mMenuPanel.add(bt4);
		bt4.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				
				mPagePanel.removeAll();
				BookInIt.init();
				mPagePanel.add("장바구니에 항목 추가하기", new CartAddItemPage(mPagePanel, mCart));
				mPagePanel.revalidate();
				mPagePanel.repaint();
			}
		});
		
		// <장바구니의 항목 수량 줄이기> 버튼 표시를 위한 패널 영역 설정 및 출력
		JButton bt5 = new JButton("장바구니에 항목수량 줄이기", new ImageIcon("src/images/5.png"));
		bt5.setFont(ft);
		mMenuPanel.add(bt5);
		
		// <장바구니의 항목 삭제하기> 버튼 표시를 위한 패널 영역 설정 및 출력
		JButton bt6 = new JButton("장바구니에 항목삭제하기", new ImageIcon("src/images/6.png"));
		bt6.setFont(ft);
		mMenuPanel.add(bt6);
		
		bt6.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				
				if (mCart.mCartCount == 0)
					JOptionPane.showMessageDialog(bt3, "장바구니에 항목이 없습니다", "장바구니 비우기", JOptionPane.ERROR_MESSAGE);
				else {
					
					mPagePanel.removeAll();
					CartItemListPage cartList = new CartItemListPage(mPagePanel, mCart);
					if (mCart.mCartCount == 0)
						JOptionPane.showMessageDialog(bt6, "장바구니에 항목이 없습니다");
					else if (cartList.mSelectRow == -1)
						JOptionPane.showMessageDialog(bt6, "장바구니에서 삭제할 항목을 선택하세요");
					else {
						mCart.removeCart(cartList.mSelectRow);
						cartList.mSelectRow = -1;
					}
				}
				mPagePanel.add("장바구니의 항목 삭제하기", new CartItemListPage(mPagePanel, mCart));
				
				mPagePanel.revalidate();
				mPagePanel.repaint();
			}
		});
		
		// <주문하기> 버튼 표시를 위한 패널 영역 설정 및 출력
		JButton bt7 = new JButton("주문하기", new ImageIcon("src/images/7.png"));
		bt7.setFont(ft);
		mMenuPanel.add(bt7);
		
		bt7.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				
				if (mCart.mCartCount == 0)
					JOptionPane.showMessageDialog(bt7, "장바구니에 항목이 없습니다", "주문처리", JOptionPane.ERROR_MESSAGE);
				else {
					
					mPagePanel.removeAll();
					mPagePanel.add("주문 배송지", new CartShippingPage(mPagePanel, mCart));
					mPagePanel.revalidate();
					mPagePanel.repaint();
				}
			}
		});
		
		// <종료> 버튼 표시를 위한 패널 영역 설정 및 출력
		JButton bt8 = new JButton("종료", new ImageIcon("src/images/8.png"));
		bt8.setFont(ft);
		mMenuPanel.add(bt8);
		
		bt8.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				
				int select = JOptionPane.showConfirmDialog(bt8, "쇼핑몰을 종료하겠습니까? ");
				
				if (select == 0) {
					System.exit(1);
				}
			}
		});
		
		// <관리자> 버튼 표시를 위한 패널 영역 설정 및 출력
		JButton bt9 = new JButton("관리자", new ImageIcon("src/images/9.png"));
		bt9.setFont(ft);
		mMenuPanel.add(bt9);
		
		bt9.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				AdminLoginDialog adminDialog;
				JFrame frame = new JFrame();
				adminDialog = new AdminLoginDialog(frame, "관리자 로그인");
				adminDialog.setVisible(true);
				if (adminDialog.isLogin) {
					mPagePanel.removeAll();
					mPagePanel.add("관리자", new AdminPage(mPagePanel));
					mPagePanel.revalidate();
					mPagePanel.repaint();
				}
			}
		});
		
	}
	
	private void initMenu() {
		Font ft;
		ft = new Font("함초롬돋움", Font.BOLD, 15);
		
		JMenuBar menuBar = new JMenuBar();
		
		JMenu menu01 = new JMenu("고객");
		menu01.setFont(ft);
		JMenuItem item01 = new JMenuItem("고객 정보");
		JMenuItem item11 = new JMenuItem("종료");
		menu01.add(item01);
		menu01.add(item11);
		menuBar.add(menu01);
		
		JMenu menu02 = new JMenu("상품");
		menu02.setFont(ft);
		JMenuItem item02 = new JMenuItem("상품 목록");
		menu02.add(item02);
		menuBar.add(menu02);
		
		JMenu menu03 = new JMenu("장바구니");
		menu03.setFont(ft);
		JMenuItem item03 = new JMenuItem("항목 추가");
		JMenuItem item04 = new JMenuItem("항목 수량 줄이기");
		JMenuItem item05 = new JMenuItem("항목 삭제하기");
		JMenuItem item06 = new JMenuItem("장바구니 비우기");
		menu03.add(item03);
		menu03.add(item04);
		menu03.add(item05);
		menu03.add(item06);
		menuBar.add(menu03);
		
		JMenu menu04 = new JMenu("주문");
		menu04.setFont(ft);
		JMenuItem item07 = new JMenuItem("영수증 표시");
		menu04.add(item07);
		menuBar.add(menu04);
		setJMenuBar(menuBar);
		
		item01.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				mPagePanel.removeAll();
				mPagePanel.add("고객 정보 확인 ", new GuestInfoPage(mPagePanel));
				add(mPagePanel);
				mPagePanel.revalidate();
			}
		});
		
		item02.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				mPagePanel.removeAll();
				BookInIt.init();
				mPagePanel.add("장바구니에 항목 추가하기", new CartAddItemPage(mPagePanel, mCart));
				add(mPagePanel);
				mPagePanel.revalidate();
			}
		});
		
		item11.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				mPagePanel.removeAll();
				setVisible(false);
				new GuestWindow("고객 정보 입력", 0, 0, 1000, 750);
				add(mPagePanel);
				mPagePanel.revalidate();
			}
		});
	}
	
	private void menuCartClear(JButton button) {
		
		if (mCart.mCartCount == 0)
			JOptionPane.showMessageDialog(button, "장바구니의 항목이 없습니다");
		else {
			
			int select = JOptionPane.showConfirmDialog(button, "장바구니의 모든 항목을 삭제하겠습니까? ");
			
			if (select == 0) {
				mCart.deleteBook();
				JOptionPane.showMessageDialog(button, "장바구니의 모든 항목을 삭제했습니다");
			}
		}
	}
}

 

com.market.page 패키지

- GuestInfoPage 클래스 수정

package com.market.page;

import javax.swing.*;

import com.market.member.UserInIt;

import java.awt.*;

public class GuestInfoPage extends JPanel {

	public GuestInfoPage(JPanel panel) {
		Font ft;
		ft = new Font("함초롬돋움", Font.BOLD, 15); // 글꼴, 스타일, 크기 설정
		
		setLayout(null);
		
		Rectangle rect = panel.getBounds();
		System.out.println(rect);
		setPreferredSize(rect.getSize());
		
		// 이름 표시를 위한 패널 영역 설정 및 출력
		JPanel namePanel = new JPanel();
		namePanel.setBounds(0, 100, 1000, 50);
		add(namePanel);
		JLabel nameLabel = new JLabel("이   름 : ");
		nameLabel.setFont(ft);
		nameLabel.setBackground(Color.BLUE);
		
		JLabel nameField = new JLabel();
		// nameField.setText("입력된 고객 이름");
		nameField.setText(UserInIt.getmUser().getName());
		nameField.setFont(ft);
		
		namePanel.add(nameLabel);
		namePanel.add(nameField);
		
		// 연락처 표시를 위한 패널 영역 설정 및 출력
		JPanel phonePanel = new JPanel();
		phonePanel.setBounds(0, 150, 1000, 100);
		add(phonePanel);
		JLabel phoneLabel = new JLabel("연락처 : ");
		phoneLabel.setFont(ft);
		JLabel phoneField = new JLabel();
		// phoneField.setText("입력된 고객 연락처");
		phoneField.setText(String.valueOf(UserInIt.getmUser().getPhone()));
		phoneField.setFont(ft);
		
		phonePanel.add(phoneLabel);
		phonePanel.add(phoneField);
	}
}

 

- CartAddItemPage 클래스 수정

package com.market.page;

import javax.swing.*;
import com.market.bookitem.Book;
import com.market.bookitem.BookInIt;
import com.market.cart.Cart;
import java.awt.*;
import java.util.ArrayList;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

public class CartAddItemPage extends JPanel {
	
	ImageIcon imageBook;
	int mSelectRow = 0;
	
	Cart mCart;
	
	public CartAddItemPage(JPanel panel, Cart cart) {
		Font ft;
		ft = new Font("함초롬돋움", Font.BOLD, 15); // 글꼴, 스타일, 크기 설정
		
		setLayout(null);
		
		Rectangle rect = panel.getBounds();
		System.out.println(rect);
		setPreferredSize(rect.getSize());
		
		mCart = cart;
		
		// 도서 이밎 표시를 위한 패널 영역 설정 및 출력 
		JPanel imagePanel = new JPanel();
		imagePanel.setBounds(20, 0, 300, 400);
		imageBook = new ImageIcon("src/images/ISBN1234.jpg");
		imageBook.setImage(imageBook.getImage().getScaledInstance(250, 300, Image.SCALE_DEFAULT));
		JLabel label = new JLabel(imageBook);
		imagePanel.add(label);
		add(imagePanel);
		
		// 도서 목록 테이블 표시를 위한 패널 영역 설정 및 출력
		JPanel tablePanel = new JPanel();
		tablePanel.setBounds(300, 0, 700, 400);
		add(tablePanel);
		
		ArrayList<Book> booklist = BookInIt.getmBookList();
		Object[] tableHeader = { "도서ID", "도서명", "가격", "저자", "설명", "분야", "출판일" };
		Object[][] content = new Object[booklist.size()][tableHeader.length];
		for (int i = 0; i < booklist.size(); i++) {
			Book bookitem = booklist.get(i);
			content[i][0] = bookitem.getBookId();
			content[i][1] = bookitem.getName();
			content[i][2] = bookitem.getUnitPrice();
			content[i][3] = bookitem.getAuthor();
			content[i][4] = bookitem.getDescription();
			content[i][5] = bookitem.getCategory();
			content[i][6] = bookitem.getReleaseDate();
			
		}
		
		JTable bookTable = new JTable(content, tableHeader);
		bookTable.setRowSelectionInterval(0, 0);
		bookTable.getSelectedColumn();
		JScrollPane jScrollPane = new JScrollPane();
		jScrollPane.setPreferredSize(new Dimension(600, 350));
		jScrollPane.setViewportView(bookTable);
		tablePanel.add(jScrollPane);
		
		// <장바구니에 담기> 버튼 표시를 위한 패널 영역 설정 및 출력
		JPanel buttonPanel = new JPanel();
		buttonPanel.setBounds(0, 400, 1000, 400);
		add(buttonPanel);
		JLabel buttonLabel = new JLabel("장바구니에 담기");
		buttonLabel.setFont(ft);
		JButton addButton = new JButton();
		addButton.add(buttonLabel);
		buttonPanel.add(addButton);
		
		bookTable.addMouseListener(new MouseListener() { // 도서 목록 테이블의 행 선택에 대한 마우스 이벤트 처리

			public void mouseClicked(MouseEvent e) { // 마우스 클릭 이벤트 처리
				int row = bookTable.getSelectedRow();
				int col = bookTable.getSelectedColumn();
				mSelectRow = row;
				Object value = bookTable.getValueAt(row, 0);
				String str = value + ".jpg";

				imageBook = new ImageIcon("./images/" + str);
				imageBook.setImage(imageBook.getImage().getScaledInstance(250, 300, Image.SCALE_DEFAULT));
				JLabel label = new JLabel(imageBook);
				imagePanel.removeAll();
				imagePanel.add(label);
				imagePanel.revalidate();
				imagePanel.repaint();
			}

			@Override
			public void mousePressed(MouseEvent e) {
				// TODO Auto-generated method stub
			}

			@Override
			public void mouseReleased(MouseEvent e) {
				// TODO Auto-generated method stub
			}

			@Override
			public void mouseEntered(MouseEvent e) {
				// TODO Auto-generated method stub
			}

			@Override
			public void mouseExited(MouseEvent e) {
				// TODO Auto-generated method stub
			}
		});

		addButton.addActionListener(new ActionListener() { // 장바구니 담기 버튼 클릭 이벤트 처리
			public void actionPerformed(ActionEvent e) {

				ArrayList<Book> booklist = BookInIt.getmBookList();
				int select = JOptionPane.showConfirmDialog(addButton, "장바구니에 추가하겠습니까?");
				if (select == 0) {
					int numId = mSelectRow;
					if (!isCartInBook(booklist.get(numId).getBookId())) {
						mCart.insertBook(booklist.get(numId));
					}
					JOptionPane.showMessageDialog(addButton, "추가했습니다");
				}
			}
		});

	}

	public boolean isCartInBook(String bookId) {
		return mCart.isCartInBook(bookId);
	}
}

 

- CartItemListPage 클래스 수정

package com.market.page;

import javax.swing.*;
import com.market.cart.Cart;
import com.market.cart.CartItem;
import java.awt.*;
import java.util.ArrayList;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import java.awt.event.ActionEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;


public class CartItemListPage extends JPanel {
	
	JTable cartTable;
	Object[] tableHeader = { "도서ID", "도서명", "단가", "수량", "총가격" };
	
	Cart mCart = new Cart();
	public static int mSelectRow = -1;
	
	public CartItemListPage(JPanel panel, Cart cart) {
		Font ft;
		ft = new Font("함초롬돋움", Font.BOLD, 15); // 글꼴, 스타일, 크기 설정
		
		this.mCart = cart;
		this.setLayout(null);
		
		Rectangle rect = panel.getBounds();
		System.out.println(rect);
		this.setPreferredSize(rect.getSize());
		
		// 도서가 담긴 장바구니의 테이블 표시를 위한 패널 영역 설정 및 출력
		JPanel bookPanel = new JPanel();
		bookPanel.setBounds(0, 0, 1000, 400);
		add(bookPanel);
		
		ArrayList<CartItem> cartItem = mCart.getmCartItem();
		Object[][] content = new Object[cartItem.size()][tableHeader.length];
		Integer totalPrice = 0;
		for (int i = 0; i < cartItem.size(); i++) {
			CartItem item = cartItem.get(i);
			content[i][0] = item.getBookID();
			content[i][1] = item.getItemBook().getName();
			content[i][2] = item.getItemBook().getUnitPrice();
			content[i][3] = item.getQuantity();
			content[i][4] = item.getTotalPrice();
			totalPrice += item.getQuantity() * item.getItemBook().getUnitPrice();
		}
		
		cartTable = new JTable(content, tableHeader);
		JScrollPane jScrollPane = new JScrollPane();
		jScrollPane.setPreferredSize(new Dimension(600, 350));
		jScrollPane.setViewportView(cartTable);
		bookPanel.add(jScrollPane);
		
		// 총 금액 표시를 위한 패널 영역 설정 및 출력
		JPanel totalPricePanel = new JPanel();
		totalPricePanel.setBounds(0, 400, 1000, 50);
		// totalPricePanel.setBackground(Color.RED);
		JLabel totalPricelabel = new JLabel("총금액: " + totalPrice + " 원");
		totalPricelabel.setForeground(Color.red);
		totalPricelabel.setFont(ft);
		totalPricePanel.add(totalPricelabel);
		add(totalPricePanel);
		
		// <장바구니 비우기>, <장바구니의 항목 삭제하기>, <장바구니 새로 고침> 버튼 표시를 위한 패널 영역 설정 및 출력
		JPanel buttonPanel = new JPanel();
		buttonPanel.setLayout(new FlowLayout());
		buttonPanel.setBounds(0, 450, 1000, 50);
		add(buttonPanel);
		
		JLabel buttonLabel = new JLabel("장바구니 비우기");
		buttonLabel.setFont(ft);
		JButton clearButton = new JButton();
		clearButton.add(buttonLabel);
		buttonPanel.add(clearButton);
		
		clearButton.addActionListener(new AbstractAction() {
			public void actionPerformed(ActionEvent e) {
				ArrayList<CartItem> cartItem = cart.getmCartItem();
				if (cart.mCartCount == 0)
					JOptionPane.showMessageDialog(clearButton, "장바구니에 항목이 없습니다");
				else {
					int select = JOptionPane.showConfirmDialog(clearButton, "장바구니의 모든 항목을 삭제하겠습니까? ");
					if (select == 0) {
						TableModel tableModel = new DefaultTableModel(new Object[0][0], tableHeader);
						cartTable.setModel(tableModel);
						totalPricelabel.setText("총금액: " + 0 + " 원");

						JOptionPane.showMessageDialog(clearButton, "장바구니의 모든 항목을 삭제했습니다");

						cart.deleteBook();
					}
				}
			}
		});
		
		JLabel removeLabel = new JLabel("장바구니의 항목 삭제하기");
		removeLabel.setFont(ft);
		JButton removeButton = new JButton();
		removeButton.add(removeLabel);
		buttonPanel.add(removeButton);
		
		removeButton.addActionListener(new AbstractAction() {
			public void actionPerformed(ActionEvent e) {
				if (cart.mCartCount == 0)
					JOptionPane.showMessageDialog(clearButton, "장바구니에 항목이 없습니다");
				else if (mSelectRow == -1)
					JOptionPane.showMessageDialog(clearButton, "장바구니에서 삭제할 항목을 선택하세요");
				else {
					ArrayList<CartItem> cartItem = cart.getmCartItem();
					cartItem.remove(mSelectRow);
					cart.mCartCount -= 1;
					Object[][] content = new Object[cartItem.size()][tableHeader.length];
					Integer totalPrice = 0;
					for (int i = 0; i < cartItem.size(); i++) {
						CartItem item = cartItem.get(i);
						content[i][0] = item.getBookID();
						content[i][1] = item.getItemBook().getName();
						content[i][2] = item.getItemBook().getUnitPrice();
						content[i][3] = item.getQuantity();
						content[i][4] = item.getTotalPrice();
						totalPrice += item.getQuantity() * item.getItemBook().getUnitPrice();
					}
					TableModel tableModel = new DefaultTableModel(content, tableHeader);
					totalPricelabel.setText("총금액: " + totalPrice + " 원");
					cartTable.setModel(tableModel);
					mSelectRow = -1;
				}
			}
		});

		cartTable.addMouseListener(new MouseListener() { // 장바구니 테이블의 행 선택에 대한 이벤트 처리

			public void mouseClicked(MouseEvent e) {
				int row = cartTable.getSelectedRow();
				mSelectRow = row;
			}

			@Override
			public void mousePressed(MouseEvent e) {
				// TODO Auto-generated method stub
			}

			@Override
			public void mouseReleased(MouseEvent e) {
				// TODO Auto-generated method stub
			}

			@Override
			public void mouseEntered(MouseEvent e) {
				// TODO Auto-generated method stub
			}

			@Override
			public void mouseExited(MouseEvent e) {
				// TODO Auto-generated method stub
			}

		});
		
		JLabel refreshLabel = new JLabel("장바구니 새로 고침");
		refreshLabel.setFont(ft);
		JButton refreshButton = new JButton();
		refreshButton.add(refreshLabel);
		buttonPanel.add(refreshButton);
		
		refreshButton.addActionListener(new AbstractAction() {
			public void actionPerformed(ActionEvent e) {
				ArrayList<CartItem> cartItem = cart.getmCartItem();
				Object[][] content = new Object[cartItem.size()][tableHeader.length];
				Integer totalPrice = 0;
				for (int i = 0; i < cartItem.size(); i++) {
					CartItem item = cartItem.get(i);
					content[i][0] = item.getBookID();
					content[i][1] = item.getItemBook().getName();
					content[i][2] = item.getItemBook().getUnitPrice();
					content[i][3] = item.getQuantity();
					content[i][4] = item.getTotalPrice();
					totalPrice += item.getQuantity() * item.getItemBook().getUnitPrice();
				}
				TableModel tableModel = new DefaultTableModel(content, tableHeader);
				totalPricelabel.setText("총금액: " + totalPrice + " 원");
				cartTable.setModel(tableModel);
			}
		});
	}
}

 

- CartShippingPage 클래스 수정

package com.market.page;

import javax.swing.*;
import java.awt.*;
import com.market.cart.Cart;
import com.market.member.UserInIt;
import java.awt.event.ActionEvent;

public class CartShippingPage extends JPanel {
	
	Cart mCart;
	JPanel shippingPanel;
	JPanel radioPanel;
	
	public CartShippingPage(JPanel panel, Cart cart) {

		Font ft;
		ft = new Font("함초롬돋움", Font.BOLD, 15); // 글꼴, 스타일, 크기 설정

		setLayout(null);

		Rectangle rect = panel.getBounds();
		System.out.println(rect);
		setPreferredSize(rect.getSize());
		
		// 고객 정보 라디오버튼 선택 표시를 위한 패널 영역 설정 및 출력
		radioPanel = new JPanel();
		radioPanel.setBounds(300, 0, 700, 50);
		radioPanel.setLayout(new FlowLayout());
		add(radioPanel);
		JLabel radioLabel = new JLabel("배송받을 분은 고객정보와 같습니까?");
		radioLabel.setFont(ft);
		JRadioButton radioOk = new JRadioButton("예");
		radioOk.setFont(ft);
		JRadioButton radioNo = new JRadioButton("아니오");
		radioNo.setFont(ft);
		radioPanel.add(radioLabel);
		radioPanel.add(radioOk);
		radioPanel.add(radioNo);
		
		// 배송지 입력, 영수증 표시를 위한 패널 영역 설정 및 출력
		shippingPanel = new JPanel();
		shippingPanel.setBounds(200, 50, 700, 500);
		shippingPanel.setLayout(null);
		add(shippingPanel);
		
		radioOk.setSelected(true);
		radioNo.setSelected(false);
		UserShippingInfo(true);
		
		this.mCart = cart;
		
		radioOk.addActionListener(new AbstractAction() { // 예 라디오버튼 클릭 이벤트 처리
			public void actionPerformed(ActionEvent e) {
				
				if (radioOk.isSelected()) {
					shippingPanel.removeAll();
					UserShippingInfo(true);
					shippingPanel.revalidate();
					shippingPanel.repaint();
					radioNo.setSelected(false);
				}
			}
		});
		
		radioNo.addActionListener(new AbstractAction() { // 아니요 라디오버튼 클릭 이벤트 처리
			public void actionPerformed(ActionEvent e) {
				
				if (radioNo.isSelected()) {
					shippingPanel.removeAll();
					UserShippingInfo(false);
					shippingPanel.revalidate();
					shippingPanel.repaint();
					radioOk.setSelected(false);
				}
			}
		});
	}

	public void UserShippingInfo(boolean select) {
		
		Font ft;
		ft = new Font("함초롬돋움", Font.BOLD, 15);
		
		// 고객명 표시를 위한 패널 영역 설정 및 출력
		JPanel namePanel = new JPanel();
		namePanel.setBounds(0, 100, 700, 50);
		// namePanel.setBackground(Color.GRAY);
		JLabel nameLabel = new JLabel("고객명 : ");
		nameLabel.setFont(ft);
		namePanel.add(nameLabel);
		
		JTextField nameLabel2 = new JTextField(15);
		nameLabel2.setFont(ft);
		if (select) {
			nameLabel2.setBackground(Color.LIGHT_GRAY);
			// nameLabel2.setText("입력된 고객 이름");
			nameLabel2.setText(UserInIt.getmUser().getName());
		}
		namePanel.add(nameLabel2);
		shippingPanel.add(namePanel);
		
		// 연락처 표시를 위한 패널 영역 설정 및 출력
		JPanel phonePanel = new JPanel();
		phonePanel.setBounds(0, 150, 700, 50);
		JLabel phoneLabel = new JLabel("연락처 : ");
		phoneLabel.setFont(ft);
		phonePanel.add(phoneLabel);
		
		JTextField phoneLabel2 = new JTextField(15);
		phoneLabel2.setFont(ft);
		if (select) {
			phoneLabel2.setBackground(Color.LIGHT_GRAY);
			// phoneLabel2.setText("입력된 고객 연락처");
			phoneLabel2.setText(String.valueOf(UserInIt.getmUser().getPhone()));
		}
		phonePanel.add(phoneLabel2);
		shippingPanel.add(phonePanel);
		
		// 배송지 표시를 위한 패널 영역 설정 및 출력
		JPanel addressPanel = new JPanel();
		addressPanel.setBounds(0, 200, 700, 50);
		JLabel label = new JLabel("배송지 : ");
		label.setFont(ft);
		addressPanel.add(label);
		
		JTextField addressText = new JTextField(15);
		addressText.setFont(ft);
		addressPanel.add(addressText);
		shippingPanel.add(addressPanel);
		
		// <주문 완려> 버튼 표시를 위한 패널 영역 설정 및 출력
		JPanel buttonPanel = new JPanel();
		buttonPanel.setBounds(0, 300, 700, 100);
		
		JLabel buttonLabel = new JLabel("주문 완료");
		buttonLabel.setFont(new Font("함초롬돋움", Font.BOLD, 15));
		JButton orderButton = new JButton();
		orderButton.add(buttonLabel);
		buttonPanel.add(orderButton);
		shippingPanel.add(buttonPanel);
		
		orderButton.addActionListener(new AbstractAction() {
			public void actionPerformed(ActionEvent e) {

				radioPanel.removeAll();

				radioPanel.revalidate();

				radioPanel.repaint();
				shippingPanel.removeAll();

				shippingPanel.add("주문 배송지", new CartOrderBillPage(shippingPanel, mCart));

				mCart.deleteBook();
				shippingPanel.revalidate();
				shippingPanel.repaint();

			}
		});
	}
}

 

- CartOrderBillPage 클래스 수정

package com.market.page;

import javax.swing.*;

import com.market.bookitem.BookInIt;
import com.market.cart.Cart;
import com.market.member.UserInIt;

import java.awt.*;
import java.text.SimpleDateFormat;
import java.util.Date;

public class CartOrderBillPage extends JPanel {
	
	Cart mCart;
	JPanel shippingPanel;
	JPanel radioPanel;
	
	public CartOrderBillPage(JPanel panel, Cart cart) {
		
		Font ft;
		ft = new Font("함초롬돋움", Font.BOLD, 15);
		
		setLayout(null);
		
		Rectangle rect = panel.getBounds();
		System.out.println(rect);
		setPreferredSize(rect.getSize());
		
		this.mCart = cart;
		
		// 주문 내용 결과 표시를 위한 패널 영역 설정 및 출력
		shippingPanel = new JPanel();
		// shippingPanel.setBounds(200, 50, 700, 500);
		shippingPanel.setBounds(0, 0, 700, 500);
		shippingPanel.setLayout(null);
		// add(shippingPanel);
		panel.add(shippingPanel);
		
		// printBillInfo("입력된 고객 이름", "입력된 고객 연락처", "입력된 고객 배송지");
		printBillInfo(UserInIt.getmUser().getName(), String.valueOf(UserInIt.getmUser().getPhone()), UserInIt.getmUser().getAddress());
		
	}
	
	public void printBillInfo(String name, String phone, String address) {
		
		Font ft;
		ft = new Font("함초롬돋움", Font.BOLD, 15); // 글꼴, 스타일, 크기 설정
		
		Date date = new Date();
		SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
		String strDate = formatter.format(date);
		
		// -배송받을 고객 정보 표시를 위한 패널 영역 설정 및 출력
		JPanel panel01 = new JPanel();
		panel01.setBounds(0, 0, 500, 30);
		// panel01.setBackground(Color.GRAY);
		JLabel label01 = new JLabel("---------------------배송받을 고객 정보-----------------------");
		label01.setFont(ft);
		panel01.add(label01);
		shippingPanel.add(panel01);
		
		// 고객명, 연락처 표시를 위한 패널 영역 설정 및 출력
		JPanel panel02 = new JPanel();
		panel02.setBounds(0, 30, 500, 30);
		JLabel label02 = new JLabel("고객명 : " + name + "             연락처 :      " + phone);
		label02.setHorizontalAlignment(JLabel.LEFT);
		label02.setFont(ft);
		panel02.add(label02);
		shippingPanel.add(panel02);
		
		// 배송지, 발송일 표시를 위한 패녈 영역 설정 및 출력
		JPanel panel03 = new JPanel();
		panel03.setBounds(0, 60, 500, 30);
		JLabel label03 = new JLabel("배송지 : " + address + "                 발송일 :       " + strDate);
		label03.setHorizontalAlignment(JLabel.LEFT);
		label03.setFont(ft);
		panel03.add(label03);
		shippingPanel.add(panel03);
		
		// 주문 도서 목록 표시를 위한 패널 영역 설정 및 출력
		JPanel printPanel = new JPanel();
		printPanel.setBounds(0, 100, 500, 300);
		printCart(printPanel);
		shippingPanel.add(printPanel);
	}
	
	public void printCart(JPanel panel) {
		
		Font ft;
		ft = new Font("함초롬돋움", Font.BOLD, 12);
		
		// 장바구니 상품 목록 표시를 위한 패널 영역 설정 및 출력
		JPanel panel01 = new JPanel();
		panel01.setBounds(0, 0, 500, 5);
		JLabel label01 = new JLabel("      장바구니 상품 목록 :");
		label01.setFont(ft);
		panel01.add(label01);
		panel.add(panel01);
		
		// ---- 표시를 위한 패널 영역 설정 및 출력
		JPanel panel02 = new JPanel();
		panel02.setBounds(0, 20, 500, 5);
		JLabel label02 = new JLabel("------------------------------------");
		label02.setFont(ft);
		panel02.add(label02);
		panel.add(panel02);
		
		// 타이틀 표시를 위한 패널 영역 설정 및 출력
		JPanel panel03 = new JPanel();
		panel03.setBounds(0, 25, 500, 5);
		JLabel label03 = new JLabel("      도서ID           |        수량           |      합계         ");
		label03.setFont(ft);
		panel03.add(label03);
		panel.add(panel03);
		
		// ---- 표시를 위한 패널 영역 설정 및 출력
		JPanel panel04 = new JPanel();
		panel04.setBounds(0, 30, 500, 5);
		JLabel label04 = new JLabel("--------------------------------------");
		label04.setFont(ft);
		panel04.add(label04);
		panel.add(panel04);
		
		for (int i = 0; i < mCart.mCartItem.size(); i++) { // 13 // 장바구니 주문 결과 표시를 위한 패널 영역 설정 및 출력
			JPanel panel05 = new JPanel();
			panel05.setBounds(0, 35 + (i * 5), 500, 5);
			JLabel label05 = new JLabel("    " + mCart.mCartItem.get(i).getBookID() + "                 "
					+ mCart.mCartItem.get(i).getQuantity() + "                "
					+ mCart.mCartItem.get(i).getTotalPrice());
			label05.setFont(ft);
			panel05.add(label05);
			panel.add(panel05);
		}
		
		// ---- 표시를 위한 패널 영역 설정 및 출력
		JPanel panel06 = new JPanel();
		panel06.setBounds(0, 35 + (mCart.mCartItem.size() * 5), 500, 5);
		JLabel label06 = new JLabel("--------------------------------------");
		label06.setFont(ft);
		panel06.add(label06);
		panel.add(panel06);
		
		int sum = 0;
		
		for (int i = 0; i < mCart.mCartCount; i++)
			sum += mCart.mCartItem.get(i).getTotalPrice();
		System.out.println("------------" + mCart.mCartCount);
		
		// 주문 총금액 표시를 위한 패널 영역 설정 및 출력
		JPanel panel07 = new JPanel();
		panel07.setBounds(0, 40 + (mCart.mCartItem.size() * 5), 500, 5);
		JLabel label07 = new JLabel("      주문 총금액 : " + sum + "원");
		// label04.setHorizontalAlignment(JLabel.CENTER);
		label07.setFont(new Font("함초롬돋움", Font.BOLD, 15));
		panel07.add(label07);
		panel.add(panel07);
		
	}
}

 

- AdminLoginDialog 클래스 생성

package com.market.page;

import com.market.member.Admin;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;

public class AdminLoginDialog extends JDialog {
	
	JTextField pwField, idField;
	public boolean isLogin = false;
	
	public AdminLoginDialog(JFrame frame, String str) {
		super(frame, "관리자로그인", true);
		
		Font ft;
		ft = new Font("함초롬돋움", Font.BOLD, 15);
		
		Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
		setLocation((screenSize.width - 400) / 2, (screenSize.height - 300) / 2);
		setSize(400, 300);
		setLayout(null);
		
		// 관리자 로그인 표시를 위한 패널 영역 설정 및 출력
		JPanel titlePanel = new JPanel();
		titlePanel.setBounds(0, 20, 400, 50);
		add(titlePanel);
		JLabel titleLabel = new JLabel("관리자 로그인");
		titleLabel.setFont(new Font("함초롬돋움", Font.BOLD, 20));
		titlePanel.add(titleLabel);
		
		// 아이디 표시를 위한 패널 영역 설정 및 출력
		JPanel idPanel = new JPanel();
		idPanel.setBounds(0, 70, 400, 50);
		add(idPanel);
		JLabel idLabel = new JLabel("아 이 디 : ");
		idLabel.setFont(ft);
		idField = new JTextField(10);
		idField.setFont(ft);
		idPanel.add(idLabel);
		idPanel.add(idField);
		
		// 비밀번호 표시를 위한 패널 영역 설정 및 출력
		JPanel pwPanel = new JPanel();
		pwPanel.setBounds(0, 120, 400, 50);
		add(pwPanel);
		JLabel pwLabel = new JLabel("비밀번호 : ");
		pwLabel.setFont(ft);
		pwField = new JTextField(10);
		pwField.setFont(ft);
		pwPanel.add(pwLabel);
		pwPanel.add(pwField);
		
		// 확인, 취소 표시를 위한 패널 영역 설정 및 출력
		JPanel buttonPanel = new JPanel();
		buttonPanel.setBounds(0, 170, 400, 50);
		add(buttonPanel);
		JLabel okLabel = new JLabel("확인");
		okLabel.setFont(ft);
		JButton okButton = new JButton();
		okButton.add(okLabel);
		buttonPanel.add(okButton);
		
		JLabel cancelLabel = new JLabel("취소");
		cancelLabel.setFont(ft);
		JButton cancelBtn = new JButton();
		cancelBtn.add(cancelLabel);
		buttonPanel.add(cancelBtn);
		
		okButton.addActionListener(new ActionListener() { // 확인 버튼 클릭 이벤트 처리
			public void actionPerformed(ActionEvent e) {

				Admin admin = new Admin("", -1);
				System.out.println(pwField.getText() + idField.getText());
				System.out.println(admin.getId() + admin.getPassword());
				if (admin.getId().equals(idField.getText()) && admin.getPassword().equals(pwField.getText())) {
					isLogin = true;
					dispose();
				} else
					JOptionPane.showMessageDialog(okButton, "관리자 정보가 일치하지 않습니다");
			}
		});
		
		cancelBtn.addActionListener(new ActionListener() { // 취소 버튼 클릭 이벤트 처리
			public void actionPerformed(ActionEvent e) {
				isLogin = false;
				dispose();
			}
		});
	}
}

 

- AdminPage 클래스 수정

package com.market.page;

import javax.swing.*;
import java.awt.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.awt.event.ActionEvent;
import java.io.FileWriter;

public class AdminPage extends JPanel {
	
	public AdminPage(JPanel panel) {
		
		Font ft;
		ft = new Font("함초롬돋움", Font.BOLD, 15); // 글꼴, 스타일, 크기 설정
		
		setLayout(null);
		
		Rectangle rect = panel.getBounds();
		System.out.println(rect);
		setPreferredSize(rect.getSize());
		
		Date date = new Date();
		SimpleDateFormat formatter = new SimpleDateFormat("yyMMddhhmmss");
		String strDate = formatter.format(date);
		
		// 도서 ID 표시를 위한 패널 영역 설정 및 출력
		JPanel idPanel = new JPanel();
		idPanel.setBounds(100, 0, 700, 50);
		JLabel idLabel = new JLabel("도서ID : ");
		idLabel.setFont(ft);
		JLabel idTextField = new JLabel();
		idTextField.setFont(ft);
		idTextField.setPreferredSize(new Dimension(290, 50));
		idTextField.setText("ISBN" + strDate);
		idPanel.add(idLabel);
		idPanel.add(idTextField);
		add(idPanel);
		
		// 도서명 표시를 위한 패널 영역 설정 및 출력
		JPanel namePanel = new JPanel();
		namePanel.setBounds(100, 50, 700, 50);
		JLabel nameLabel = new JLabel("도서명 : ");
		nameLabel.setFont(ft);
		JTextField nameTextField = new JTextField(20);
		nameTextField.setFont(ft);
		namePanel.add(nameLabel);
		namePanel.add(nameTextField);
		add(namePanel);
		
		// 가격 표시를 위한 패널 영역 설정 및 출력
		JPanel pricePanel = new JPanel();
		pricePanel.setBounds(100, 100, 700, 50);
		JLabel priceLabel = new JLabel("가   격 : ");
		priceLabel.setFont(ft);
		JTextField priceTextField = new JTextField(20);
		priceTextField.setFont(ft);
		pricePanel.add(priceLabel);
		pricePanel.add(priceTextField);
		add(pricePanel);
		
		// 저자 표시를 위한 패널 영역 설정 및 출력
		JPanel authorPanel = new JPanel();
		authorPanel.setBounds(100, 150, 700, 50);
		JLabel authorLabel = new JLabel("저   자 : ");
		authorLabel.setFont(ft);
		JTextField authorTextField = new JTextField(20);
		authorTextField.setFont(ft);
		authorPanel.add(authorLabel);
		authorPanel.add(authorTextField);
		add(authorPanel);
		
		// 설명 표시를 위한 패널 영역 설정 및 출력
		JPanel descPanel = new JPanel();
		descPanel.setBounds(100, 200, 700, 50);
		JLabel descLabel = new JLabel("설   명 : ");
		descLabel.setFont(ft);
		JTextField descTextField = new JTextField(20);
		descTextField.setFont(ft);
		descPanel.add(descLabel);
		descPanel.add(descTextField);
		add(descPanel);
		
		//분야 표시를 위한 패널 영역 설정 및 출력
		JPanel categoryPanel = new JPanel();
		categoryPanel.setBounds(100, 250, 700, 50);
		JLabel categoryLabel = new JLabel("분   야 : ");
		categoryLabel.setFont(ft);
		JTextField categoryTextField = new JTextField(20);
		categoryTextField.setFont(ft);
		categoryPanel.add(categoryLabel);
		categoryPanel.add(categoryTextField);
		add(categoryPanel);
		
		//출판일 표시를 위한 패널 영역 설정 및 출력
		JPanel datePanel = new JPanel();
		datePanel.setBounds(100, 300, 700, 50);
		JLabel dateLabel = new JLabel("출판일 : ");
		dateLabel.setFont(ft);
		JTextField dateTextField = new JTextField(20);
		dateTextField.setFont(ft);
		datePanel.add(dateLabel);
		datePanel.add(dateTextField);
		add(datePanel);
		
		//<추가>, <취소> 버튼 표시를 위한 패널 영역 설정 및 출력
		JPanel buttonPanel = new JPanel();
		buttonPanel.setBounds(100, 350, 700, 50);
		add(buttonPanel);
		JLabel okLabel = new JLabel("추가");
		okLabel.setFont(ft);
		JButton okButton = new JButton();
		okButton.add(okLabel);
		buttonPanel.add(okButton);
		
		okButton.addActionListener(new AbstractAction() { // 추가 버튼 클릭 이벤트 처리
			public void actionPerformed(ActionEvent e) {
				String[] writeBook = new String[7];
				writeBook[0] = idTextField.getText();
				writeBook[1] = nameTextField.getText();
				writeBook[2] = priceTextField.getText();
				writeBook[3] = authorTextField.getText();
				writeBook[4] = descTextField.getText();
				writeBook[5] = categoryTextField.getText();
				writeBook[6] = dateTextField.getText();
				try {
					FileWriter fw = new FileWriter("book.txt", true);
					for (int i = 0; i < 7; i++)
						fw.write(writeBook[i] + "\n");
					fw.close();
					JOptionPane.showMessageDialog(okButton, "새 도서 정보가 저장되었습니다");

					Date date = new Date();
					SimpleDateFormat formatter = new SimpleDateFormat("yyMMddhhmmss");
					String strDate = formatter.format(date);

					idTextField.setText("ISBN" + strDate);
					nameTextField.setText("");
					priceTextField.setText("");
					authorTextField.setText("");
					descTextField.setText("");
					categoryTextField.setText("");
					dateTextField.setText("");

					System.out.println("새 도서 정보가 저장되었습니다.");
				} catch (Exception ex) {
					System.out.println(ex);
				}
			}
		});
		
		JLabel noLabel = new JLabel("취소");
		noLabel.setFont(ft);
		JButton noButton = new JButton();
		noButton.add(noLabel);
		buttonPanel.add(noButton);
		
		noButton.addActionListener(new AbstractAction() { // 취소 버튼 클릭 이벤트 처리
			public void actionPerformed(ActionEvent e) {

				nameTextField.setText("");
				priceTextField.setText("");
				authorTextField.setText("");
				descTextField.setText("");
				categoryTextField.setText("");
				dateTextField.setText("");
			}
		});
	}
}

 

'한빛아카데미 - JAVA 마스터' 교재의 프로젝트 내용입니다.


프로젝트 구조도

 

BookMarketSwing 프로젝트

 

PART13 화면 GUI 구성하기

BookMarketSwing - 프로젝트 생성

 

BookMarket 프로젝트의 com.market.member 패키지 이동

- UserInit 클래스 생성

package com.market.member;

public class UserInIt {
	private static User mUser;
	
	public static void setmUser(User mUser) {
		UserInIt.mUser = mUser;
	}
	
	public static void init(String name, int phone) {
		mUser = new User(name, phone);
	}

	public static User getmUser() {
		return mUser;
	}

	
	
}

 

BookMarket 프로젝트의 com.market.bookitem 패키지 이동

- BookInIt 클래스 생성

package com.market.bookitem;

import java.io.*;
import java.util.ArrayList;

public class BookInIt {
	private static ArrayList<Book> mBookList;
	private static int mTotalBook = 0;
	
	public static void init() {
		
		mTotalBook = totalFileToBookList();
		mBookList = new ArrayList<Book>();
		setFileToBookList(mBookList);	
		
	}
	
	public static int totalFileToBookList() { // 파일에서 도서의 개수를 얻는 메서드 // BookMarket 프로젝트의 Welcome 클래스 메서드
		try {
			FileReader fr = new FileReader("book.txt"); // book.txt 파일을 읽기 위한 FileReder 객체 생성
			BufferedReader reader = new BufferedReader(fr); // 파일에서 한 행씩 읽기 위한 BufferedReader 객체 생성

			String str;
			int num = 0;
			while ((str = reader.readLine()) != null) { // 파일에서 읽을 행이 없을 때 까지 반복
				if (str.contains("ISBN")) // 파일에서 읽은 한 행에 문자열 "ISBN"이 포함되어 있으면 도서의 개수 num을 1 증가시킴
					++num;
			}

			reader.close(); // BufferedReader 객체 종료
			fr.close(); // FileReader 객체 종료
			return num;
		} catch (Exception e) {
			System.out.println(e);
		}
		return 0;
	}
	
	public static void setFileToBookList(ArrayList<Book> booklist) { // 파일에서 도서 정보 목록을 읽어 저장하는 매서드 // BookMarket 프로젝트의 Welcome 클래스 메서드
		try {
			FileReader fr = new FileReader("book.txt"); // book.txt 파일을 읽기 위한 FileReder 객체 생성
			BufferedReader reader = new BufferedReader(fr); // 파일에서 한 행씩 읽기 위한 BufferedReader 객체 생성

			String str2;
			String[] readBook = new String[7];

			while ((str2 = reader.readLine()) != null) { // 파일에서 읽을 행이 없을 때까지 반복
				if (str2.contains("ISBN")) { // 파일에서 읽은 한 행에 문자열 "ISBN"이 포함되어 있으면 도서 정보에 대해 한 행씩 읽어 지역변수 readBook에 저장
					readBook[0] = str2;
					readBook[1] = reader.readLine();
					readBook[2] = reader.readLine();
					readBook[3] = reader.readLine();
					readBook[4] = reader.readLine();
					readBook[5] = reader.readLine();
					readBook[6] = reader.readLine();
				}

				Book bookitem = new Book(readBook[0], readBook[1], Integer.parseInt(readBook[2]), readBook[3], readBook[4], readBook[5], readBook[6]);
				
				booklist.add(bookitem);

			}

			reader.close(); // BufferedReader 객체 종료
			fr.close(); // FileReader 객체 종료

		} catch (Exception e) {
			System.out.println(e);
		}
	}
	
	public static ArrayList<Book> getmBookList() { // 도서 목록 불러오는 메서드
		return mBookList;
		
	}
	
	public static void setmBookList(ArrayList<Book> mBookList) { // 도서 목록 저장하는 메서드
		BookInIt.mBookList = mBookList;
	}
	
	public static int getmTotalBook() { // 총 도서 수량 불러오는 메서드
		return mTotalBook;
	}
	
	public static void setmTotalBook(int mTotalBook) { // 총 도서 수량 저장하는 메서드
		BookInIt.mTotalBook = mTotalBook;
	}
	
	
}

 

BookMarket 프로젝트의 com.market.cart 패키지 이동

- Cart.java 의 getter(), setter() 메서드 추가

package com.market.cart;

import java.util.ArrayList;
import com.market.bookitem.Book; // Book 클래스 사용하기 위한 선언

public class Cart implements CartInterface { // CartInterface 인터페이스의 자식 클래스 Cart 생성
	public ArrayList<CartItem> mCartItem = new ArrayList<CartItem>(); // mCartItem은 ArrayList 클래스를 이용하여 장바구니에 항목을 담는 객체 변수
	public static int mCartCount = 0; // 장바구니에 담긴 항목의 총 개수를 저장하는 변수
	
	public Cart() { // Cart 클래스의 기본 생성자

	}
	
	public ArrayList<CartItem> getmCartItem(){ // 장바구니의 도서 항목 불러오는 메서드 
		return mCartItem;
	}
	
	public void setmCartItem(ArrayList<CartItem> mCartItem) { // 장바구니의 도서 항목 저장하는 메서드
		this.mCartItem = mCartItem;
	}

	public void printBookList(ArrayList<Book> booklist) { // Book[] booklist -> ArrayList<Book> 전체 도서 정보 목록 출력 구현

		for (int i = 0; i < booklist.size(); i++) {
			Book bookitem = booklist.get(i);
			System.out.print(bookitem.getBookId() + " | ");
			System.out.print(bookitem.getName() + " | ");
			System.out.print(bookitem.getUnitPrice() + " | ");
			System.out.print(bookitem.getAuthor() + " | ");
			System.out.print(bookitem.getDescription() + " | ");
			System.out.print(bookitem.getCategory() + " | ");
			System.out.print(bookitem.getReleaseDate() + " | ");
			System.out.println("");
		}

	}


	public void insertBook(Book book) { // CartItem에 도서 정보를 등록하는 메서드 구현
		CartItem bookitem = new CartItem(book);
		mCartItem.add(bookitem);
		mCartCount = mCartItem.size();
	}

	public void deleteBook() { // 장바구니의 모든 항목을 삭제하는 메서드 구현
		mCartItem.clear();
		mCartCount = 0;
	}

	public void printCart() {
		System.out.println("장바구니 상품 목록 :");
		System.out.println("-----------------------------------------------");
		System.out.println("       도서ID \t|     수 량 \t|       합 계");
	
		for (int i = 0; i < mCartCount; i++) {
			System.out.print("     " + mCartItem.get(i).getBookID() + "\t| ");
			System.out.print("     " + mCartItem.get(i).getQuantity() + "\t| ");
			System.out.print("     " + mCartItem.get(i).getTotalPrice());
			System.out.println("  ");
		}
		
		System.out.println("-----------------------------------------------");
	}

	public boolean isCartInBook(String bookId) { // 장바구니에 담긴 도서의 ID와 장바구니에 담을 도서의 ID를 비교하는 메서드 구현
		boolean flag = false;

		for (int i = 0; i < mCartItem.size(); i++) {
			if (bookId == mCartItem.get(i).getBookID()) {
				mCartItem.get(i).setQuantity(mCartItem.get(i).getQuantity() + 1);
				flag = true;
			}
		}

		return flag;
	}

	public void removeCart(int numId) { // 장바구니 순번 numId의 항목을 삭제하는 메서드 구현
		mCartItem.remove(numId);
		mCartCount = mCartItem.size();
	}

}

 

com.market.main 패키지 생성

- GuestWindow 클래스 생성

- MainWindow 클래스 생성

package com.market.main;

import javax.swing.*;
import java.awt.*;

public class GuestWindow extends JFrame {
	
	public GuestWindow(String title, int x, int y, int width, int height) {
		initContainer(title, x, y, width, height); // initContainer() 메서드 호출
		setVisible(true); // 프레임 보이기 설정
		setResizable(true); // 프레임 크기 조절 가능 설정
		setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); // 프레임 닫기 버튼 가능 설정
		setIconImage(new ImageIcon("src/images/shop.png").getImage()); // 프레임 아이콘 표시 // ./images/shop.png 이미지 불러오지 못함
	}
	
	private void initContainer(String title, int x, int y, int width, int height) {
		setTitle(title); // 프레임 제목 설정
		setBounds(x, y, width, height); // 프레임 위치, 크기 설정
		setLayout(null); // 프레임 레이아웃 미설정
		
		Font ft;
		ft = new Font("함초롬돋움", Font.BOLD, 15); // 글꼴, 스타일, 크기 설정
		
		Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
		setLocation((screenSize.width - 1000) / 2, (screenSize.height - 750 ) / 2); // 컴퓨터 화면에 맞춰 프레임 창을 화면 중앙에 출력
		
		// user.png 이미지 표시를 위한 패널 영역 설정 및 출력
		JPanel userPanel = new JPanel();
		userPanel.setBounds(0, 100, 1000, 256);
		
		ImageIcon imageIcon = new ImageIcon("src/images/user.png");  // ./images/user.png 이미지 불러오지 못함
		imageIcon.setImage(imageIcon.getImage().getScaledInstance(160, 160, Image.SCALE_SMOOTH));
		JLabel userLabel = new JLabel(imageIcon);
		userPanel.add(userLabel);
		add(userPanel);
		
		// -- 고객 정보를 입력하세요 -- 표시를 위한 패널 영역 설정 및 출력
		
		JPanel titlePanel = new JPanel();
		titlePanel.setBounds(0, 350, 1000, 50);
		add(titlePanel);
		
		JLabel titleLabel = new JLabel("-- 고객 정보를 입력하세요 --");
		titleLabel.setFont(ft); // JLabel인 titleLabel 글꼴 설정
		titleLabel.setForeground(Color.BLUE); // JLabel인 titleLabel 문자열 색상 설정
		titlePanel.add(titleLabel);
		
		// 이름 표시를 위한 패널 영역 설정 및 출력
		JPanel namePanel = new JPanel();
		namePanel.setBounds(0, 400, 1000, 50);
		add(namePanel);
		
		JLabel nameLabel = new JLabel("이   름 : ");
		nameLabel.setFont(ft);
		namePanel.add(nameLabel);
		
		// 이름 표시를 위한 패널 영역 설정 및 출력
		JTextField nameField = new JTextField(10);
		nameField.setFont(ft);
		namePanel.add(nameField);
		
		// 연락처 표시를 위한 패널 영역 설정 및 출력
		JPanel phonePanel = new JPanel();
		phonePanel.setBounds(0, 450, 1000, 50);
		add(phonePanel);
		
		JLabel phoneLabel = new JLabel("연락처 : ");
		phonePanel.setFont(ft);
		phonePanel.add(phoneLabel);
		
		JTextField phoneField = new JTextField(10);
		phonePanel.setFont(ft);
		phonePanel.add(phoneField);
		
		// <쇼핑하기> 버튼 표시를 위한 패널 영역 설정 및 출력
		JPanel buttonPanel = new JPanel();
		buttonPanel.setBounds(0, 500, 1000, 100);
		add(buttonPanel);
		

		JLabel buttonLabel = new JLabel("쇼핑하기", new ImageIcon("src/images/shop.png"), JLabel.LEFT);   // images/shop.png 이미지 불러오지 못함
		buttonLabel.setFont(ft);
		JButton enterButton = new JButton();
		enterButton.add(buttonLabel);
		buttonPanel.add(enterButton);
	} 
	
//	public static void main(String[] args) {
//		 new GuestWindow("고객 정보 입력", 0, 0, 1000, 750); // 테스트 화면 창을 띄우기 위한 실행용 메서드
//	}

}

 

package com.market.main;

import javax.swing.*;
import java.awt.*;

public class MainWindow extends JFrame {
	
	static JPanel mMenuPanel, mPagePanel;
	
	public MainWindow(String title, int x, int y, int width, int height) {
		initContainer(title, x, y, width, height); // initContainer() 메서드 호출
		setVisible(true); // 프레임 보이기 설정
		setResizable(true); // 프레임 크기 조절 가능 설정
		setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); // 프레임 닫기 버튼 가능 설정
		setIconImage(new ImageIcon("src/images/shop.png").getImage()); // 프레임 아이콘 표시 // ./images/shop.png 이미지 불러오지 못함
	}
	
	private void initContainer(String title, int x, int y, int width, int height) {
		setTitle(title); // 프레임 제목 설정
		setBounds(x, y, width, height); // 프레임 위치, 크기 설정
		setLayout(null); // 프레임 레이아웃 미설정
		
		Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
		setLocation((screenSize.width - 1000) / 2, (screenSize.height - 750 ) / 2); // 컴퓨터 화면에 맞춰 프레임 창을 화면 중앙에 출력
		
		//메뉴 버튼 표시를 위한 프레임 상단의 패널 영역 설정 및 출력
		mMenuPanel = new JPanel();
		mMenuPanel.setBounds(0, 20, width, 130);
		menuIntroduction();
		add(mMenuPanel);
		
		// 메뉴 버튼별 클릭 시 페이지 표시를 위한 프레임 하단의 패널 영역 설정 및 출력
		mPagePanel = new JPanel();
		mPagePanel.setBounds(0, 150, width, height);
		add(mPagePanel);
		
	}
	
	private void menuIntroduction() {
		Font ft;
		ft = new Font("함초롬돋움", Font.BOLD, 15); // 글꼴, 스타일, 크기 설정
		
		// <고객 정보 확인하기> 버튼 표시를 위한 패널 영역 설정 및 출력
		JButton bt1 = new JButton("고객 정보 확인하기", new ImageIcon("src/images/1.png"));
		bt1.setBounds(0, 0, 100, 50);
		bt1.setFont(ft);
		mMenuPanel.add(bt1);
		
		// <장바구니 상품 목록보기> 버튼 표시를 위한 패널 영역 설정 및 출력
		JButton bt2 = new JButton("장바구니 상품 목록보기", new ImageIcon("src/images/2.png"));
		bt2.setBounds(0, 0, 100, 30);
		bt2.setFont(ft);
		mMenuPanel.add(bt2);
		
		// <장바구니 비우기> 버튼 표시를 위한 패널 영역 설정 및 출력
		JButton bt3 = new JButton("장바구니 비우기", new ImageIcon("src/images/3.png"));
		bt3.setBounds(0, 0, 100, 30);
		bt3.setFont(ft);
		mMenuPanel.add(bt3);
		
		// <장바구니에 항목 추가하기> 버튼 표시를 위한 패널 영역 설정 및 출력
		JButton bt4 = new JButton("장바구니에 항목 추가하기", new ImageIcon("src/images/4.png"));
		bt4.setFont(ft);
		mMenuPanel.add(bt4);
		
		// <장바구니의 항목 수량 줄이기> 버튼 표시를 위한 패널 영역 설정 및 출력
		JButton bt5 = new JButton("장바구니의 항목 수량 줄이기", new ImageIcon("src/images/5.png"));
		bt5.setFont(ft);
		mMenuPanel.add(bt5);
		
		// <장바구니의 항목 삭제하기> 버튼 표시를 위한 패널 영역 설정 및 출력
		JButton bt6 = new JButton("장바구니의 항목 삭제하기", new ImageIcon("src/images/6.png"));
		bt6.setFont(ft);
		mMenuPanel.add(bt6);
		
		// <주문하기> 버튼 표시를 위한 패널 영역 설정 및 출력
		JButton bt7 = new JButton("주문하기", new ImageIcon("src/images/7.png"));
		bt7.setFont(ft);
		mMenuPanel.add(bt7);
		
		// <종료> 버튼 표시를 위한 패널 영역 설정 및 출력
		JButton bt8 = new JButton("종료", new ImageIcon("src/images/8.png"));
		bt8.setFont(ft);
		mMenuPanel.add(bt8);
		
		// <관리자> 버튼 표시를 위한 패널 영역 설정 및 출력
		JButton bt9 = new JButton("관리자", new ImageIcon("src/images/9.png"));
		bt9.setFont(ft);
		mMenuPanel.add(bt9);
		
	}
	
//	public static void main(String[] args) {
//		 new MainWindow("도서 쇼핑몰", 0, 0, 1000, 750); // 테스트 화면 창을 띄우기 위한 실행용 메서드
//	}
}

 

com.market.page 패키지 생성

- GuestInfoPage, CartAddItemPage, CartItemListPage, CartShippingPage, CartOrderBillPage, AdminPage 클래스 생성

package com.market.page;

import javax.swing.*;
import java.awt.*;

public class GuestInfoPage extends JPanel {

	public GuestInfoPage(JPanel panel) {
		Font ft;
		ft = new Font("함초롬돋움", Font.BOLD, 15); // 글꼴, 스타일, 크기 설정
		
		setLayout(null);
		
		Rectangle rect = panel.getBounds();
		System.out.println(rect);
		setPreferredSize(rect.getSize());
		
		// 이름 표시를 위한 패널 영역 설정 및 출력
		JPanel namePanel = new JPanel();
		namePanel.setBounds(0, 100, 1000, 50);
		add(namePanel);
		JLabel nameLabel = new JLabel("이   름 : ");
		nameLabel.setFont(ft);
		nameLabel.setBackground(Color.BLUE);
		
		JLabel nameField = new JLabel();
		nameField.setText("입력된 고객 이름");
		nameField.setFont(ft);
		
		namePanel.add(nameLabel);
		namePanel.add(nameField);
		
		// 연락처 표시를 위한 패널 영역 설정 및 출력
		JPanel phonePanel = new JPanel();
		phonePanel.setBounds(0, 150, 1000, 100);
		add(phonePanel);
		JLabel phoneLabel = new JLabel("연락처 : ");
		phoneLabel.setFont(ft);
		JLabel phoneField = new JLabel();
		phoneField.setText("입력된 고객 연락처");
		phoneField.setFont(ft);
		
		phonePanel.add(phoneLabel);
		phonePanel.add(phoneField);
	}
	
//	public static void main(String[] args) { // 테스트 화면 창을 띄우기 위한 실행용 메서드
//		JFrame frame = new JFrame();
//		frame.setBounds(0, 0, 1000, 750);
//		frame.setLayout(null);
//
//		JPanel mPagePanel = new JPanel();
//		mPagePanel.setBounds(0, 150, 1000, 750);
//
//		frame.add(mPagePanel);
//		mPagePanel.add("고객 정보 확인하기", new GuestInfoPage(mPagePanel));
//		frame.setVisible(true);
//	}
}

 

package com.market.page;

import javax.swing.*;
import com.market.bookitem.Book;
import com.market.bookitem.BookInIt;
import com.market.cart.Cart;
import java.awt.*;
import java.util.ArrayList;

public class CartAddItemPage extends JPanel {
	
	ImageIcon imageBook;
	int mSelectRow = 0;
	
	Cart mCart;
	
	public CartAddItemPage(JPanel panel, Cart cart) {
		Font ft;
		ft = new Font("함초롬돋움", Font.BOLD, 15); // 글꼴, 스타일, 크기 설정
		
		setLayout(null);
		
		Rectangle rect = panel.getBounds();
		System.out.println(rect);
		setPreferredSize(rect.getSize());
		
		mCart = cart;
		
		// 도서 이밎 표시를 위한 패널 영역 설정 및 출력 
		JPanel imagePanel = new JPanel();
		imagePanel.setBounds(20, 0, 300, 400);
		imageBook = new ImageIcon("src/images/ISBN1234.jpg");
		imageBook.setImage(imageBook.getImage().getScaledInstance(250, 300, Image.SCALE_DEFAULT));
		JLabel label = new JLabel(imageBook);
		imagePanel.add(label);
		add(imagePanel);
		
		// 도서 목록 테이블 표시를 위한 패널 영역 설정 및 출력
		JPanel tablePanel = new JPanel();
		tablePanel.setBounds(300, 0, 700, 400);
		add(tablePanel);
		
		ArrayList<Book> booklist = BookInIt.getmBookList();
		Object[] tableHeader = { "도서ID", "도서명", "가격", "저자", "설명", "분야", "출판일" };
		Object[][] content = new Object[booklist.size()][tableHeader.length];
		for (int i = 0; i < booklist.size(); i++) {
			Book bookitem = booklist.get(i);
			content[i][0] = bookitem.getBookId();
			content[i][1] = bookitem.getName();
			content[i][2] = bookitem.getUnitPrice();
			content[i][3] = bookitem.getAuthor();
			content[i][4] = bookitem.getDescription();
			content[i][5] = bookitem.getCategory();
			content[i][6] = bookitem.getReleaseDate();
			
		}
		
		JTable bookTable = new JTable(content, tableHeader);
		bookTable.setRowSelectionInterval(0, 0);
		bookTable.getSelectedColumn();
		JScrollPane jScrollPane = new JScrollPane();
		jScrollPane.setPreferredSize(new Dimension(600, 350));
		jScrollPane.setViewportView(bookTable);
		tablePanel.add(jScrollPane);
		
		// <장바구니에 담기> 버튼 표시를 위한 패널 영역 설정 및 출력
		JPanel buttonPanel = new JPanel();
		buttonPanel.setBounds(0, 400, 1000, 400);
		add(buttonPanel);
		JLabel buttonLabel = new JLabel("장바구니에 담기");
		buttonLabel.setFont(ft);
		JButton addButton = new JButton();
		addButton.add(buttonLabel);
		buttonPanel.add(addButton);
	}
	
//	public static void main(String[] args) {  // 테스트 화면 창을 띄우기 위한 실행용 메서드
//		Cart mCart = new Cart();
//		JFrame frame = new JFrame();
//		frame.setBounds(0, 0, 1000, 750);
//		frame.setLayout(null);
//		
//		JPanel mPagePanel = new JPanel();
//		mPagePanel.setBounds(0, 150, 1000, 750);
//		frame.add(mPagePanel);
//		
//		BookInIt.init();
//		mPagePanel.add("장바구니에 항목 추가하기", new CartAddItemPage(mPagePanel, mCart));
//		frame.setVisible(true);
//	}
}

 

package com.market.page;

import javax.swing.*;
import com.market.cart.Cart;
import com.market.cart.CartItem;
import java.awt.*;
import java.util.ArrayList;


public class CartItemListPage extends JPanel {
	
	JTable cartTable;
	Object[] tableHeader = { "도서ID", "도서명", "단가", "수량", "총가격" };
	
	Cart mCart = new Cart();
	public static int mSelectRow = -1;
	
	public CartItemListPage(JPanel panel, Cart cart) {
		Font ft;
		ft = new Font("함초롬돋움", Font.BOLD, 15); // 글꼴, 스타일, 크기 설정
		
		this.mCart = cart;
		this.setLayout(null);
		
		Rectangle rect = panel.getBounds();
		System.out.println(rect);
		this.setPreferredSize(rect.getSize());
		
		// 도서가 담긴 장바구니의 테이블 표시를 위한 패널 영역 설정 및 출력
		JPanel bookPanel = new JPanel();
		bookPanel.setBounds(0, 0, 1000, 400);
		add(bookPanel);
		
		ArrayList<CartItem> cartItem = mCart.getmCartItem();
		Object[][] content = new Object[cartItem.size()][tableHeader.length];
		Integer totalPrice = 0;
		for (int i = 0; i < cartItem.size(); i++) {
			CartItem item = cartItem.get(i);
			content[i][0] = item.getBookID();
			content[i][1] = item.getItemBook().getName();
			content[i][2] = item.getItemBook().getUnitPrice();
			content[i][3] = item.getQuantity();
			content[i][4] = item.getTotalPrice();
			totalPrice += item.getQuantity() * item.getItemBook().getUnitPrice();
		}
		
		cartTable = new JTable(content, tableHeader);
		JScrollPane jScrollPane = new JScrollPane();
		jScrollPane.setPreferredSize(new Dimension(600, 350));
		jScrollPane.setViewportView(cartTable);
		bookPanel.add(jScrollPane);
		
		// 총 금액 표시를 위한 패널 영역 설정 및 출력
		JPanel totalPricePanel = new JPanel();
		totalPricePanel.setBounds(0, 400, 1000, 50);
		// totalPricePanel.setBackground(Color.RED);
		JLabel totalPricelabel = new JLabel("총금액: " + totalPrice + " 원");
		totalPricelabel.setForeground(Color.red);
		totalPricelabel.setFont(ft);
		totalPricePanel.add(totalPricelabel);
		add(totalPricePanel);
		
		// <장바구니 비우기>, <장바구니의 항목 삭제하기>, <장바구니 새로 고침> 버튼 표시를 위한 패널 영역 설정 및 출력
		JPanel buttonPanel = new JPanel();
		buttonPanel.setLayout(new FlowLayout());
		buttonPanel.setBounds(0, 450, 1000, 50);
		add(buttonPanel);
		
		JLabel buttonLabel = new JLabel("장바구니 비우기");
		buttonLabel.setFont(ft);
		JButton clearButton = new JButton();
		clearButton.add(buttonLabel);
		buttonPanel.add(clearButton);
		
		JLabel removeLabel = new JLabel("장바구니의 항목 삭제하기");
		removeLabel.setFont(ft);
		JButton removeButton = new JButton();
		removeButton.add(removeLabel);
		buttonPanel.add(removeButton);
		
		JLabel refreshLabel = new JLabel("장바구니 새로 고침");
		refreshLabel.setFont(ft);
		JButton refreshButton = new JButton();
		refreshButton.add(refreshLabel);
		buttonPanel.add(refreshButton);
	}
	
//	public static void main(String[] args) {  // 테스트 화면 창을 띄우기 위한 실행용 메서드
//		
//		Cart mCart = new Cart();
//		JFrame frame = new JFrame();
//		frame.setBounds(0, 0, 1000, 750);
//		frame.setLayout(null);
//		
//		JPanel mPagePanel = new JPanel();
//		mPagePanel.setBounds(0, 150, 1000, 750);
//		
//		frame.add(mPagePanel);
//		mPagePanel.add("장바구니의 상품 목록 보기", new CartItemListPage(mPagePanel, mCart));
//		frame.setVisible(true);
//	}
}

 

package com.market.page;

import javax.swing.*;
import java.awt.*;

public class CartShippingPage extends JPanel {
	
	JPanel shippingPanel;
	JPanel radioPanel;
	
	public CartShippingPage(JPanel panel) {
		
		Font ft;
		ft = new Font("함초롬돋움", Font.BOLD, 15); // 글꼴, 스타일, 크기 설정
		
		setLayout(null);
		
		Rectangle rect = panel.getBounds();
		System.out.println(rect);
		setPreferredSize(rect.getSize());
		
		// 고객 정보 라디오버튼 선택 표시를 위한 패널 영역 설정 및 출력
		radioPanel = new JPanel();
		radioPanel.setBounds(300, 0, 700, 50);
		radioPanel.setLayout(new FlowLayout());
		add(radioPanel);
		JLabel radioLabel = new JLabel("배송받을 분은 고객 정보와 같습니까?");
		radioLabel.setFont(ft);
		JRadioButton radioOk = new JRadioButton("예");
		radioOk.setFont(ft);
		JRadioButton radioNo = new JRadioButton("아니요");
		radioNo.setFont(ft);
		radioPanel.add(radioLabel);
		radioPanel.add(radioOk);
		radioPanel.add(radioNo);
		
		// 배송지 입력, 영수증 표시를 위한 패널 영역 설정 및 출력
		shippingPanel = new JPanel();
		shippingPanel.setBounds(200, 50, 700, 500);
		shippingPanel.setLayout(null);
		add(shippingPanel);
		
		radioOk.setSelected(true);
		radioNo.setSelected(false);
		UserShippingInfo(true);
	}
	
	public void UserShippingInfo(boolean select) {
		
		Font ft;
		ft = new Font("함초롬돋움", Font.BOLD, 15);
		
		// 고객명 표시를 위한 패널 영역 설정 및 출력
		JPanel namePanel = new JPanel();
		namePanel.setBounds(0, 100, 700, 50);
		// namePanel.setBackground(Color.GRAY);
		JLabel nameLabel = new JLabel("고객명 : ");
		nameLabel.setFont(ft);
		namePanel.add(nameLabel);
		
		JTextField nameLabel2 = new JTextField(15);
		nameLabel2.setFont(ft);
		if (select) {
			nameLabel2.setBackground(Color.LIGHT_GRAY);
			nameLabel2.setText("입력된 고객 이름");
		}
		namePanel.add(nameLabel2);
		shippingPanel.add(namePanel);
		
		// 연락처 표시를 위한 패널 영역 설정 및 출력
		JPanel phonePanel = new JPanel();
		phonePanel.setBounds(0, 150, 700, 50);
		JLabel phoneLabel = new JLabel("연락처 : ");
		phoneLabel.setFont(ft);
		phonePanel.add(phoneLabel);
		
		JTextField phoneLabel2 = new JTextField(15);
		phoneLabel2.setFont(ft);
		if (select) {
			phoneLabel2.setBackground(Color.LIGHT_GRAY);
			phoneLabel2.setText("입력된 고객 연락처");
		}
		phonePanel.add(phoneLabel2);
		shippingPanel.add(phonePanel);
		
		// 배송지 표시를 위한 패널 영역 설정 및 출력
		JPanel addressPanel = new JPanel();
		addressPanel.setBounds(0, 200, 700, 50);
		JLabel label = new JLabel("배송지 : ");
		label.setFont(ft);
		addressPanel.add(label);
		
		JTextField addressText = new JTextField(15);
		addressText.setFont(ft);
		addressPanel.add(addressText);
		shippingPanel.add(addressPanel);
		
		// <주문 완려> 버튼 표시를 위한 패널 영역 설정 및 출력
		JPanel buttonPanel = new JPanel();
		buttonPanel.setBounds(0, 300, 700, 100);
		
		JLabel buttonLabel = new JLabel("주문 완료");
		buttonLabel.setFont(new Font("함초롬돋움", Font.BOLD, 15));
		JButton orderButton = new JButton();
		orderButton.add(buttonLabel);
		buttonPanel.add(orderButton);
		shippingPanel.add(buttonPanel);
	}

//	public static void main(String[] args) {   // 테스트 화면 창을 띄우기 위한 실행용 메서드
//		
//		JFrame frame = new JFrame();
//		frame.setBounds(0, 0, 1000, 750);
//		frame.setLayout(null);
//		
//		JPanel mPagePanel = new JPanel();
//		mPagePanel.setBounds(0, 150, 1000, 750);
//		
//		frame.add(mPagePanel);
//		mPagePanel.add("주문 배송지", new CartShippingPage(mPagePanel));
//		frame.setVisible(true);
//		
//	}
}

 

package com.market.page;

import javax.swing.*;

import com.market.bookitem.BookInIt;
import com.market.cart.Cart;
import java.awt.*;
import java.text.SimpleDateFormat;
import java.util.Date;

public class CartOrderBillPage extends JPanel {
	
	Cart mCart;
	JPanel shippingPanel;
	JPanel radioPanel;
	
	public CartOrderBillPage(JPanel panel, Cart cart) {
		
		Font ft;
		ft = new Font("함초롬돋움", Font.BOLD, 15);
		
		setLayout(null);
		
		Rectangle rect = panel.getBounds();
		System.out.println(rect);
		setPreferredSize(rect.getSize());
		
		this.mCart = cart;
		
		// 주문 내용 결과 표시를 위한 패널 영역 설정 및 출력
		shippingPanel = new JPanel();
		shippingPanel.setBounds(200, 50, 700, 500);
		shippingPanel.setLayout(null);
		add(shippingPanel);
		
		printBillInfo("입력된 고객 이름", "입력된 고객 연락처", "입력된 고객 배송지");
		
	}
	
	public void printBillInfo(String name, String phone, String address) {
		
		Font ft;
		ft = new Font("함초롬돋움", Font.BOLD, 15); // 글꼴, 스타일, 크기 설정
		
		Date date = new Date();
		SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
		String strDate = formatter.format(date);
		
		// -배송받을 고객 정보 표시를 위한 패널 영역 설정 및 출력
		JPanel panel01 = new JPanel();
		panel01.setBounds(0, 0, 500, 30);
		// panel01.setBackground(Color.GRAY);
		JLabel label01 = new JLabel("---------------------배송받을 고객 정보-----------------------");
		label01.setFont(ft);
		panel01.add(label01);
		shippingPanel.add(panel01);
		
		// 고객명, 연락처 표시를 위한 패널 영역 설정 및 출력
		JPanel panel02 = new JPanel();
		panel02.setBounds(0, 30, 500, 30);
		JLabel label02 = new JLabel("고객명 : " + name + "             연락처 :      " + phone);
		label02.setHorizontalAlignment(JLabel.LEFT);
		label02.setFont(ft);
		panel02.add(label02);
		shippingPanel.add(panel02);
		
		// 배송지, 발송일 표시를 위한 패녈 영역 설정 및 출력
		JPanel panel03 = new JPanel();
		panel03.setBounds(0, 60, 500, 30);
		JLabel label03 = new JLabel("배송지 : " + address + "                 발송일 :       " + strDate);
		label03.setHorizontalAlignment(JLabel.LEFT);
		label03.setFont(ft);
		panel03.add(label03);
		shippingPanel.add(panel03);
		
		// 주문 도서 목록 표시를 위한 패널 영역 설정 및 출력
		JPanel printPanel = new JPanel();
		printPanel.setBounds(0, 100, 500, 300);
		printCart(printPanel);
		shippingPanel.add(printPanel);
	}
	
	public void printCart(JPanel panel) {
		
		Font ft;
		ft = new Font("함초롬돋움", Font.BOLD, 12);
		
		// 장바구니 상품 목록 표시를 위한 패널 영역 설정 및 출력
		JPanel panel01 = new JPanel();
		panel01.setBounds(0, 0, 500, 5);
		JLabel label01 = new JLabel("      장바구니 상품 목록 :");
		label01.setFont(ft);
		panel01.add(label01);
		panel.add(panel01);
		
		// ---- 표시를 위한 패널 영역 설정 및 출력
		JPanel panel02 = new JPanel();
		panel02.setBounds(0, 20, 500, 5);
		JLabel label02 = new JLabel("------------------------------------");
		label02.setFont(ft);
		panel02.add(label02);
		panel.add(panel02);
		
		// 타이틀 표시를 위한 패널 영역 설정 및 출력
		JPanel panel03 = new JPanel();
		panel03.setBounds(0, 25, 500, 5);
		JLabel label03 = new JLabel("      도서ID           |        수량           |      합계         ");
		label03.setFont(ft);
		panel03.add(label03);
		panel.add(panel03);
		
		// ---- 표시를 위한 패널 영역 설정 및 출력
		JPanel panel04 = new JPanel();
		panel04.setBounds(0, 30, 500, 5);
		JLabel label04 = new JLabel("--------------------------------------");
		label04.setFont(ft);
		panel04.add(label04);
		panel.add(panel04);
		
		for (int i = 0; i < mCart.mCartItem.size(); i++) { // 13 // 장바구니 주문 결과 표시를 위한 패널 영역 설정 및 출력
			JPanel panel05 = new JPanel();
			panel05.setBounds(0, 35 + (i * 5), 500, 5);
			JLabel label05 = new JLabel("    " + mCart.mCartItem.get(i).getBookID() + "                 "
					+ mCart.mCartItem.get(i).getQuantity() + "                "
					+ mCart.mCartItem.get(i).getTotalPrice());
			label05.setFont(ft);
			panel05.add(label05);
			panel.add(panel05);
		}
		
		// ---- 표시를 위한 패널 영역 설정 및 출력
		JPanel panel06 = new JPanel();
		panel06.setBounds(0, 35 + (mCart.mCartItem.size() * 5), 500, 5);
		JLabel label06 = new JLabel("--------------------------------------");
		label06.setFont(ft);
		panel06.add(label06);
		panel.add(panel06);
		
		int sum = 0;
		
		for (int i = 0; i < mCart.mCartCount; i++)
			sum += mCart.mCartItem.get(i).getTotalPrice();
		System.out.println("------------" + mCart.mCartCount);
		
		// 주문 총금액 표시를 위한 패널 영역 설정 및 출력
		JPanel panel07 = new JPanel();
		panel07.setBounds(0, 40 + (mCart.mCartItem.size() * 5), 500, 5);
		JLabel label07 = new JLabel("      주문 총금액 : " + sum + "원");
		// label04.setHorizontalAlignment(JLabel.CENTER);
		label07.setFont(new Font("함초롬돋움", Font.BOLD, 15));
		panel07.add(label07);
		panel.add(panel07);
		
	}
	
//	public static void main(String[] args) {   // 테스트 화면 창을 띄우기 위한 실행용 메서드
//		
//		Cart mCart = new Cart();
//		JFrame frame = new JFrame();
//		frame.setBounds(0, 0, 1000, 750);
//		frame.setLayout(null);
//		
//		JPanel mPagePanel = new JPanel();
//		mPagePanel.setBounds(0, 150, 1000, 750);
//		
//		frame.add(mPagePanel);
//		BookInIt.init();
//		mPagePanel.add("주문하기", new CartOrderBillPage(mPagePanel, mCart));
//		frame.setVisible(true);
//		
//	}
}

 

package com.market.page;

import javax.swing.*;
import java.awt.*;
import java.text.SimpleDateFormat;
import java.util.Date;

public class AdminPage extends JPanel {
	
	public AdminPage(JPanel panel) {
		
		Font ft;
		ft = new Font("함초롬돋움", Font.BOLD, 15); // 글꼴, 스타일, 크기 설정
		
		setLayout(null);
		
		Rectangle rect = panel.getBounds();
		System.out.println(rect);
		setPreferredSize(rect.getSize());
		
		Date date = new Date();
		SimpleDateFormat formatter = new SimpleDateFormat("yyMMddhhmmss");
		String strDate = formatter.format(date);
		
		// 도서 ID 표시를 위한 패널 영역 설정 및 출력
		JPanel idPanel = new JPanel();
		idPanel.setBounds(100, 0, 700, 50);
		JLabel idLabel = new JLabel("도서ID : ");
		idLabel.setFont(ft);
		JLabel idTextField = new JLabel();
		idTextField.setFont(ft);
		idTextField.setPreferredSize(new Dimension(290, 50));
		idTextField.setText("ISBN" + strDate);
		idPanel.add(idLabel);
		idPanel.add(idTextField);
		add(idPanel);
		
		// 도서명 표시를 위한 패널 영역 설정 및 출력
		JPanel namePanel = new JPanel();
		namePanel.setBounds(100, 50, 700, 50);
		JLabel nameLabel = new JLabel("도서명 : ");
		nameLabel.setFont(ft);
		JTextField nameTextField = new JTextField(20);
		nameTextField.setFont(ft);
		namePanel.add(nameLabel);
		namePanel.add(nameTextField);
		add(namePanel);
		
		// 가격 표시를 위한 패널 영역 설정 및 출력
		JPanel pricePanel = new JPanel();
		pricePanel.setBounds(100, 100, 700, 50);
		JLabel priceLabel = new JLabel("가   격 : ");
		priceLabel.setFont(ft);
		JTextField priceTextField = new JTextField(20);
		priceTextField.setFont(ft);
		pricePanel.add(priceLabel);
		pricePanel.add(priceTextField);
		add(pricePanel);
		
		// 저자 표시를 위한 패널 영역 설정 및 출력
		JPanel authorPanel = new JPanel();
		authorPanel.setBounds(100, 150, 700, 50);
		JLabel authorLabel = new JLabel("저   자 : ");
		authorLabel.setFont(ft);
		JTextField authorTextField = new JTextField(20);
		authorTextField.setFont(ft);
		authorPanel.add(authorLabel);
		authorPanel.add(authorTextField);
		add(authorPanel);
		
		// 설명 표시를 위한 패널 영역 설정 및 출력
		JPanel descPanel = new JPanel();
		descPanel.setBounds(100, 200, 700, 50);
		JLabel descLabel = new JLabel("설   명 : ");
		descLabel.setFont(ft);
		JTextField descTextField = new JTextField(20);
		descTextField.setFont(ft);
		descPanel.add(descLabel);
		descPanel.add(descTextField);
		add(descPanel);
		
		//분야 표시를 위한 패널 영역 설정 및 출력
		JPanel categoryPanel = new JPanel();
		categoryPanel.setBounds(100, 250, 700, 50);
		JLabel categoryLabel = new JLabel("분   야 : ");
		categoryLabel.setFont(ft);
		JTextField categoryTextField = new JTextField(20);
		categoryTextField.setFont(ft);
		categoryPanel.add(categoryLabel);
		categoryPanel.add(categoryTextField);
		add(categoryPanel);
		
		//출판일 표시를 위한 패널 영역 설정 및 출력
		JPanel datePanel = new JPanel();
		datePanel.setBounds(100, 300, 700, 50);
		JLabel dateLabel = new JLabel("출판일 : ");
		dateLabel.setFont(ft);
		JTextField dateTextField = new JTextField(20);
		dateTextField.setFont(ft);
		datePanel.add(dateLabel);
		datePanel.add(dateTextField);
		add(datePanel);
		
		//<추가>, <취소> 버튼 표시를 위한 패널 영역 설정 및 출력
		JPanel buttonPanel = new JPanel();
		buttonPanel.setBounds(100, 350, 700, 50);
		add(buttonPanel);
		JLabel okLabel = new JLabel("추가");
		okLabel.setFont(ft);
		JButton okButton = new JButton();
		okButton.add(okLabel);
		buttonPanel.add(okButton);
		
		JLabel noLabel = new JLabel("취소");
		noLabel.setFont(ft);
		JButton noButton = new JButton();
		noButton.add(noLabel);
		buttonPanel.add(noButton);
	}
//	
//	public static void main(String[] args) {    // 테스트 화면 창을 띄우기 위한 실행용 메서드
//		
//		JFrame frame = new JFrame();
//		frame.setBounds(0, 0, 1000, 750);
//		frame.setLayout(null);
//		
//		JPanel mPagePanel = new JPanel();
//		mPagePanel.setBounds(0, 150, 1000, 750);
//		
//		frame.add(mPagePanel);
//		mPagePanel.add("주문하기", new AdminPage(mPagePanel));
//		frame.setVisible(true);
//	}
}

'한빛아카데미 - JAVA 마스터' 교재의 프로젝트 내용입니다.


프로젝트 구조도

 

프로젝트 사진

 

 

PART12 장바구니, 도서 상품, 주문 처리 개선하기

Class CartInterface - 수정

- printBookList() 수정

package com.market.cart;

import java.util.ArrayList;
import com.market.bookitem.Book; // Book 클래스 사용하기 위한 선언


public interface CartInterface { // 장바구니 처리의 메서드를 정의하기 위한 인터페이스 생성
	
	void printBookList(ArrayList<Book> p); // 전체 도서 정보 목록 출력
	boolean isCartInBook(String id); /// 장바구니에 담긴 도서의 ID와 장바구니에 담을 도서의 ID를 비교하는 메서드
	void insertBook(Book p); // CartItem에 도서 정보를 등록하는 메서드
	void removeCart(int numId); // 장바구니 순번 numId의 항목을 삭제하는 메서드
	void deleteBook(); // 장바구니의 모든 항목을 삭제하는 메서드
	
}

 

Class Cart - 수정

- printBookList(), insertBook(), deleteBook(), printCart(), isCartInBook(), removeCart() 수정

package com.market.cart;

import java.util.ArrayList;
import com.market.bookitem.Book; // Book 클래스 사용하기 위한 선언

public class Cart implements CartInterface { // CartInterface 인터페이스의 자식 클래스 Cart 생성
	public ArrayList<CartItem> mCartItem = new ArrayList<CartItem>(); // mCartItem은 ArrayList 클래스를 이용하여 장바구니에 항목을 담는 객체
																		// 변수

	// static final int NUM_BOOK = 3;  // 이전 내용 주석
	// public CartItem[] mCartItem = new CartItem[NUM_BOOK];  // 이전 내용 주석
	public static int mCartCount = 0; // 장바구니에 담긴 항목의 총 개수를 저장하는 변수

	public Cart() { // Cart 클래스의 기본 생성자

	}

	public void printBookList(ArrayList<Book> booklist) { // Book[] booklist -> ArrayList<Book> 전체 도서 정보 목록 출력 구현
		/*  이전 내용 주석
		 * for(int i = 0; i< booklist.length; i++) {
		 * System.out.print(booklist[i].getBookId() + " | ");
		 * System.out.print(booklist[i].getName() + " | ");
		 * System.out.print(booklist[i].getUnitPrice() + " | ");
		 * System.out.print(booklist[i].getAuthor() + " | ");
		 * System.out.print(booklist[i].getDescription() + " | ");
		 * System.out.print(booklist[i].getCategory() + " | ");
		 * System.out.print(booklist[i].getReleaseDate() + " | ");
		 * System.out.println("");
		 */

		for (int i = 0; i < booklist.size(); i++) {
			Book bookitem = booklist.get(i);
			System.out.print(bookitem.getBookId() + " | ");
			System.out.print(bookitem.getName() + " | ");
			System.out.print(bookitem.getUnitPrice() + " | ");
			System.out.print(bookitem.getAuthor() + " | ");
			System.out.print(bookitem.getDescription() + " | ");
			System.out.print(bookitem.getCategory() + " | ");
			System.out.print(bookitem.getReleaseDate() + " | ");
			System.out.println("");
		}

	}


	public void insertBook(Book book) { // CartItem에 도서 정보를 등록하는 메서드 구현
		// mCartItem[mCartCount++] = new CartItem(book);  이전 내용 주석

		CartItem bookitem = new CartItem(book);
		mCartItem.add(bookitem);
		mCartCount = mCartItem.size();

	}

	public void deleteBook() { // 장바구니의 모든 항목을 삭제하는 메서드 구현
		// mCartItem = new CartItem[NUM_BOOK];  이전 내용 주석

		mCartItem.clear();
		mCartCount = 0;

	}

	public void printCart() {
		System.out.println("장바구니 상품 목록 :");
		System.out.println("-----------------------------------------------");
		System.out.println("       도서ID \t|     수 량 \t|       합 계");
		/*  이전 내용 주석
		 * for(int i = 0; i < mCartCount; i++) {
		 * System.out.print("     "+mCartItem[i].getBookID() + "\t| ");
		 * System.out.print("     "+mCartItem[i].getQuantity() + "\t| ");
		 * System.out.print("     "+mCartItem[i].getTotalPrice());
		 * System.out.println("  "); }
		 */
		for (int i = 0; i < mCartCount; i++) {
			System.out.print("     " + mCartItem.get(i).getBookID() + "\t| ");
			System.out.print("     " + mCartItem.get(i).getQuantity() + "\t| ");
			System.out.print("     " + mCartItem.get(i).getTotalPrice());
			System.out.println("  ");
		}

		System.out.println("-----------------------------------------------");
	}

	public boolean isCartInBook(String bookId) { // 장바구니에 담긴 도서의 ID와 장바구니에 담을 도서의 ID를 비교하는 메서드 구현
		boolean flag = false;
		/*  이전 내용 주석
		 * for(int i = 0; i < mCartCount; i++) { if(bookId == mCartItem[i].getBookID())
		 * { mCartItem[i].setQuantity(mCartItem[i].getQuantity()+1); flag = true; } }
		 */

		for (int i = 0; i < mCartItem.size(); i++) {
			if (bookId == mCartItem.get(i).getBookID()) {
				mCartItem.get(i).setQuantity(mCartItem.get(i).getQuantity() + 1);
				flag = true;
			}
		}

		return flag;
	}

	public void removeCart(int numId) { // 장바구니 순번 numId의 항목을 삭제하는 메서드 구현
		/* 이전 내용 주석
		 * CartItem[] cartItem = new CartItem[NUM_BOOK]; int num = 0;
		 * 
		 * for (int i = 0; i < mCartCount; i++) if (numId != i) cartItem[num++] =
		 * mCartItem[i];
		 * 
		 * 
		 * mCartCount = num; mCartItem = cartItem;
		 */

		mCartItem.remove(numId);
		mCartCount = mCartItem.size();

	}

}

 

Class Welcome - 수정

- menuCartAddItem(), menuCartRemoveItem(), setFileToBookList(), printBill() 수정

package com.market.main;

import java.util.Scanner;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.ArrayList;

import com.market.bookitem.Book; // Book 클래스 사용하기 위한 선언
import com.market.cart.Cart; // Cart 클래스 사용하기 위한 선언
import com.market.member.Admin; // Admin 클래스 사용하기 위한 선언
import com.market.member.User; // User 클래스 사용하기 위한 선언
import com.market.exception.CartException; // CartException 사용하기 위한 선언

public class Welcome {
	static final int NUM_BOOK = 3; // 도서의 개수에 대한 상수 NUM_BOOK 선언
	static final int NUM_ITEM = 7; // 도서 정보의 개수에 대한 상수 NUM_ITEM 선언
	// static CartItem[] mCartItem = new CartItem[NUM_BOOK];
	// static int mCartCount = 0;
	static Cart mCart = new Cart(); // Cart 클래스를 사용하기 위한 객체 생성
	static User mUser;

	public static void menuIntroduction() { // 메뉴 출력하는 메서드
		System.out.println("***************************************");
		System.out.println(" 1. 고객 정보 확인하기 \t4. 바구니에 항목 추가하기");
		System.out.println(" 2. 장바구니 상품 목록 보기 \t5. 장바구니의 항목 수량 줄이기");
		System.out.println(" 3. 장바구니 비우기 \t6. 장바구니의 항목 삭제하기");
		System.out.println(" 7. 영수증 표시하기 \t8. 종료");
		System.out.println(" 9. 관리자 로그인");
		System.out.println("***************************************");
	}

	public static void menuGuestInfo(String name, int mobile) { // 고객 정보 확인하는 메서드
		System.out.println("현재 고객 정보 : ");
		System.out.println("이름 " + mUser.getName() + " 연락처 " + mUser.getPhone());

		// System.out.println("이름 " + name + " 연락처 " + mobile);
		// Person person = new Person(name, mobile);
		// System.out.println("이름 " + person.getName() + " 연락처 " + person.getPhone());
	}

	public static void menuCartItemList() { // 장바구니 상품 목록 확인하는 메서드
		/*
		 * System.out.println("장바구니 상품 목록 :");
		 * System.out.println("-----------------------------------------------");
		 * System.out.println("       도서ID \t|     수 량 \t|       합 계"); for(int i = 0; i
		 * < mCartCount; i++) { System.out.print("     "+mCartItem[i].getBookID() +
		 * "\t| "); System.out.print("     "+mCartItem[i].getQuantity() + "\t| ");
		 * System.out.println("     "+mCartItem[i].getTotalPrice()); }
		 * System.out.println("-----------------------------------------------");
		 */

		if (mCart.mCartCount >= 0) {
			mCart.printCart();
		}
	}

	public static void menuCartClear() throws CartException { // 장바구니 모든 항목 삭제하는 메서드
		// System.out.println("장바구니 비우기: ");
		if (mCart.mCartCount == 0) {
			throw new CartException("장바구니에 항목이 없습니다");
			// System.out.println("장바구니에 항목이 없습니다");
		} else {
			System.out.println("장바구니의 모든 항목을 삭제하겠습니까? Y | N ");
			Scanner input = new Scanner(System.in);
			String str = input.nextLine();

			if (str.toUpperCase().equals("Y")) {
				mCart.deleteBook();
			}

		}
	}

	public static void menuCartAddItem(ArrayList<Book> booklist) { // Book[] -> ArrayList<Book>  변경 매개변수 추가, 장바구니에 도서를
															// 추가하는 메서드
		// System.out.println("장바구니에 항목 추가하기 : ");

		// BookList(book); // 도서 정보를 저장하는 메서드 호출
		BookList(booklist);
		/*
		 * for (int i = 0; i < NUM_BOOK; i++) { // 도서 정보 출력 for (int j = 0; j <
		 * NUM_ITEM; j++) System.out.print(book[i][j] + " | "); System.out.println("");
		 * }
		 */
		mCart.printBookList(booklist);
		
		boolean quit = false;

		while (!quit) { // 장바구니에 항목을 추가하지 않을 때까지 반복하는 while문
			System.out.print("장바구니에 추가할 도서의 ID를 입력하세요 : ");

			Scanner input = new Scanner(System.in);
			String str = input.nextLine(); // 도서의 ID를 입력받음

			boolean flag = false;
			int numId = -1;
			/* PART 11 내용 주석
			for (int i = 0; i < NUM_BOOK; i++) { // 입력된 도서의 ID와 저장되어 있는 도서 정보의 ID가 일치하는지 확인하여
				if (str.equals(booklist[i].getBookId())) { // 일치하면 도서 정보의 numId(인덱스 번호)와 flag(일치 여부) 변수에 값을 변경하여 저장하고
															// 반복문 종료
					numId = i;
					flag = true;
					break;
				}
			}
			*/
			
			for (int i = 0; i < booklist.size(); i++) { // 입력된 도서의 ID와 저장되어 있는 도서 정보의 ID가 일치하는지 확인하여
				if (str.equals(booklist.get(i).getBookId())) { // 일치하면 도서 정보의 numId(인덱스 번호)와 flag(일치 여부) 변수에 값을 변경하여 저장하고
															// 반복문 종료
					numId = i;
					flag = true;
					break;
				}
			}

			if (flag) { // 변수 flag가 참이면(입력된 도서의 ID와 저장되어 있는 도서 정보의 ID가 일치하면) 반복문을 종료하고, 거짓이면 '다시 입력해
						// 주세요' 출력
				System.out.println("장바구니에 추가하겠습니까? Y | N");
				str = input.nextLine(); // 장바구니에 도서 추가 여부를 위한 입력값을 받음
				
				/* PART 11 내용 주석
				if (str.toUpperCase().equals("Y")) { // 입력값을 대문자로 변경하여 Y이면 '도서가 장바구니에 추가되었습니다.' 출력
					System.out.println(booklist[numId].getBookId() + "도서가 장바구니에 추가되었습니다.");

					// 장바구니에 넣기
					if (!isCartInBook(booklist[numId].getBookId()))
						mCart.insertBook(booklist[numId]);
				}
				*/
				
				if (str.toUpperCase().equals("Y")) { // 입력값을 대문자로 변경하여 Y이면 '도서가 장바구니에 추가되었습니다.' 출력
					System.out.println(booklist.get(numId).getBookId() + "도서가 장바구니에 추가되었습니다.");

					// 장바구니에 넣기
					if (!isCartInBook(booklist.get(numId).getBookId()))
						mCart.insertBook(booklist.get(numId));
				}

				quit = true;

			} else
				System.out.println("다시 입력해 주세요");
		}
	}

	public static boolean isCartInBook(String bookId) { // 장바구니에 담긴 도서의 ID와 장바구니에 담을 도서의 ID를 비교하는 메서드
		/*
		 * boolean flag = false; for(int i = 0; i < mCartCount; i++) { if(bookId ==
		 * mCartItem[i].getBookID()) {
		 * mCartItem[i].setQuantity(mCartItem[i].getQuantity()+1); flag = true; } }
		 * return flag;
		 */
		return mCart.isCartInBook(bookId);
	}

	public static void menuCartRemoveItemCount() { // 장바구니의 항목 수량 줄이는 메서드
		System.out.println("5. 장바구니의 항목 수량 줄이기");
	}

	public static void menuCartRemoveItem() throws CartException { // 장바구니의 항목 삭제하는 메서드
		// System.out.println("6. 장바구니의 항목 삭제하기");
		
		if (mCart.mCartCount == 0)
			throw new CartException("장바구니에 항목이 없습니다");
		// System.out.println("장바구니에 항목이 없습니다");
		
		else {
			menuCartItemList();
			boolean quit = false;
			while (!quit) {
				System.out.print("장바구니에서 삭제할 도서의 ID를 입력하세요 :");
				Scanner input = new Scanner(System.in);
				String str = input.nextLine();
				boolean flag = false;
				int numId = -1;

				for (int i = 0; i < mCart.mCartCount; i++) {
					// if (str.equals(mCart.mCartItem[i].getBookID())) { // PART 11 내용 주석
					
					if (str.equals(mCart.mCartItem.get(i).getBookID())) {
						numId = i;
						flag = true;
						break;
					}
				}

				if (flag) {
					System.out.println("장바구니의 항목을 삭제하시겠습니까? Y | N ");
					str = input.nextLine();
					if (str.toUpperCase().equals("Y")) {
						// System.out.println(mCart.mCartItem[numId].getBookID() + "도서가 삭제되었습니다."); // PART 11 내용 주석
						
						System.out.println(mCart.mCartItem.get(numId).getBookID() + "도서가 삭제되었습니다.");
						mCart.removeCart(numId); // Cart 클래스의 구현된 removeCart 메서드로 도서 삭제 진행
					}
					quit = true;
				} else
					System.out.println("다시 입력해 주세요");
			}
		}
	}

	public static void menuCartBill() throws CartException { // 주문 처리를 위한 고객의 정보 저장하는 메서드
		// System.out.println("7. 영수증 표시하기");
		if (mCart.mCartCount == 0)
			throw new CartException("장바구니에 항목이 없습니다");
		// System.out.println("장바구니에 항목이 없습니다.");

		else {
			System.out.println("배송받을 분은 고객 정보와 같습니까? Y | N ");
			Scanner input = new Scanner(System.in);
			String str = input.nextLine();

			if (str.toUpperCase().equals("Y")) {
				System.out.println("배송지를 입력해주세요 ");
				String address = input.nextLine();
				printBill(mUser.getName(), String.valueOf(mUser.getPhone()), address); // 배송을 위한 고객정보와 영수증 출력을 위한
																						// printBill 메서드 호출
			} else {
				System.out.print("배송받을 고객명을 입력하세요 ");
				String name = input.nextLine();
				System.out.print("배송받을 고객의 연락처를 입력하세요 ");
				String phone = input.nextLine();
				System.out.print("배송받을 고객의 배송지를 입력해주세요 ");
				String address = input.nextLine();
				printBill(name, phone, address);
			}
		}
	}

	public static void printBill(String name, String phone, String address) { // 주문 처리 후 영수증을 표시하는 메서드
		Date date = new Date(); // MM/dd/yyyy 형식의 현재 날짜 정보를 엳음
		SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
		String strDate = formatter.format(date);
		System.out.println();
		System.out.println("----------------배송받을 고객 정보-----------------");
		System.out.println("고객명 : " + name + "   \t\t연락처 : " + phone);
		System.out.println("배송지 : " + address + "   \t\t발송일 : " + strDate);

		mCart.printCart(); // 장바구니에 담긴 항목 출력

		int sum = 0;
		for (int i = 0; i < mCart.mCartCount; i++)
			// sum += mCart.mCartItem[i].getTotalPrice(); // PART 11 내용 주석
			
			sum += mCart.mCartItem.get(i).getTotalPrice();

		System.out.println("\t\t\t주문 총금액 : " + sum + "원\n");
		System.out.println("-----------------------------------------------");
		System.out.println();
	}

	public static void menuExit() { // 종료하는 메서드
		System.out.println("8. 종료");
	}

	public static void menuAdminLogin() { // 관리자 로그인 메서드
		System.out.println("관리자 정보를 입력하세요");

		Scanner input = new Scanner(System.in);
		System.out.print("아이디: ");
		String adminId = input.next();

		System.out.print("비밀번호: ");
		String adminPW = input.next();

		Admin admin = new Admin(mUser.getName(), mUser.getPhone());
		if (adminId.equals(admin.getId()) && adminPW.equals(admin.getPassword())) {
			String[] writeBook = new String[7];
			System.out.println("도서 정보를 추가하겠습니까? Y | N " );
			String str = input.next();
			
			if(str.toUpperCase().equals("Y")) {
				Date date = new Date();
				SimpleDateFormat formatter = new SimpleDateFormat("yyMMddhhmmss");
				String strDate = formatter.format(date);
				writeBook[0] = "ISBN" + strDate;
				System.out.println("도서ID : " + writeBook[0]);
				String st1 = input.nextLine(); // 키보드로 한 행 입력시 엔터키를 입력으로 처리
				System.out.print("도서명 : ");
				writeBook[1] = input.nextLine();
				System.out.print("가격 : ");
				writeBook[2] = input.nextLine();
				System.out.print("저자 : ");
				writeBook[3] = input.nextLine();
				System.out.print("설명 : ");
				writeBook[4] = input.nextLine();
				System.out.print("분야 : ");
				writeBook[5] = input.nextLine();
				System.out.print("출판일 : ");
				writeBook[6] = input.nextLine();
				
				try { // 파일 처리를 위한 try ~ catch 문
					FileWriter fw = new FileWriter("book.txt", true); // book.txt 파일에 쓰기 위해 FileWriter 객체 생성
																	  // 기존 파일에 쓰기 위해 FileWriter 생성자에 true 작성
					
					for(int i = 0; i < 7; i++) { // 새로 입력받은 도서정보를 book.txt 파일에 저장
						fw.write(writeBook[i]+"\n");
					}
					
					fw.close(); // FileWriter 객체 종료
					System.out.println("새 도서 정보가 저장되었습니다.");
					
				} catch(Exception e) {
					System.out.println(e);
				}
			}else {
				System.out.println("이름 " + admin.getName() + " 연락처 " + admin.getPhone());
				System.out.println("아이디 " + admin.getId() + " 비밀번호 " + admin.getPassword());
			}

		} else
			System.out.println("관리자 정보가 일치하지 않습니다.");
	}

	public static void BookList(ArrayList<Book> booklist) { // Book[] -> ArrayList<Book> 도서 정보를 저장하는 메서드
		setFileToBookList(booklist);
		/*
		 * booklist[0] = new Book("ISBN1234", "쉽게 배우는 JSP 웹 프로그래밍", 27000);
		 * booklist[0].setAuthor("송미영");
		 * booklist[0].setDescription("단계별로 쇼핑몰을 구현하며 배우는 JSP 웹 프로그래밍");
		 * booklist[0].setCategory("IT전문서");
		 * booklist[0].setReleaseDate("2018/10/08");
		 * 
		 * booklist[1] = new Book("ISBN1235", "안드로이드 프로그래밍", 33000);
		 * booklist[1].setAuthor("우재남");
		 * booklist[1].setDescription("실습 단계별 명쾌한 멘토링!");
		 * booklist[1].setCategory("IT전문서");
		 * booklist[1].setReleaseDate("2022/01/22");
		 *
		 * booklist[2] = new Book("ISBN1236", "스크래치", 22000);
		 * booklist[2].setAuthor("고광일");
		 * booklist[2].setDescription("컴퓨팅 사고력을 키우는 블록 코딩");
		 * booklist[2].setCategory("컴퓨터입문");
		 * booklist[2].setReleaseDate("2019/06/10");
		 */

		/*
		 * book[0][0] = "ISBN1234";
		 * book[0][1] = "쉽게 배우는 JSP 웹 프로그래밍";
		 * book[0][2] = "27000"; // 27,000 
		 * book[0][3] = "송미영";
		 * book[0][4] = "단계별로 쇼핑몰을 구현하며 배우는 JSP 웹 프로그래밍 ";
		 * book[0][5] = "IT전문서";
		 * book[0][6] = "2018/10/08";
		 * book[1][0] = "ISBN1235";
		 * book[1][1] = "안드로이드 프로그래밍";
		 * book[1][2] = "33000"; // 33,000
		 * book[1][3] = "우재남";
		 * book[1][4] = "실습 단계별 명쾌한 멘토링!";
		 * book[1][5] = "IT전문서";
		 * book[1][6] = "2022/01/22";
		 * book[2][0] = "ISBN1236";
		 * book[2][1] = "스크래치";
		 * book[2][2] = "22000"; // 22,000
		 * book[2][3] = "고광일";
		 * book[2][4] = "컴퓨팅 사고력을 키우는 블록 코딩";
		 * book[2][5] = "컴퓨터입문";
		 * book[2][6] = "2019/06/10";
		 */
	}

	public static int totalFileToBookList() { // 파일에서 도서의 개수를 얻는 메서드
		try {
			FileReader fr = new FileReader("book.txt"); // book.txt 파일을 읽기 위한 FileReder 객체 생성
			BufferedReader reader = new BufferedReader(fr); // 파일에서 한 행씩 읽기 위한 BufferedReader 객체 생성

			String str;
			int num = 0;
			while ((str = reader.readLine()) != null) { // 파일에서 읽을 행이 없을 때 까지 반복
				if (str.contains("ISBN")) // 파일에서 읽은 한 행에 문자열 "ISBN"이 포함되어 있으면 도서의 개수 num을 1 증가시킴
					++num;
			}

			reader.close(); // BufferedReader 객체 종료
			fr.close(); // FileReader 객체 종료
			return num;
		} catch (Exception e) {
			System.out.println(e);
		}
		return 0;
	}

	public static void setFileToBookList(ArrayList<Book> booklist) { // Book[] -> ArrayList<Book> 파일에서 도서 정보 목록을 읽어 저장하는 매서드
		try {
			FileReader fr = new FileReader("book.txt"); // book.txt 파일을 읽기 위한 FileReder 객체 생성
			BufferedReader reader = new BufferedReader(fr); // 파일에서 한 행씩 읽기 위한 BufferedReader 객체 생성

			String str2;
			String[] readBook = new String[7];
			// int count = 0; // PART 11 내용 주석

			while ((str2 = reader.readLine()) != null) { // 파일에서 읽을 행이 없을 때까지 반복
				if (str2.contains("ISBN")) { // 파일에서 읽은 한 행에 문자열 "ISBN"이 포함되어 있으면 도서 정보에 대해 한 행씩 읽어 지역변수 readBook에 저장
					readBook[0] = str2;
					readBook[1] = reader.readLine();
					readBook[2] = reader.readLine();
					readBook[3] = reader.readLine();
					readBook[4] = reader.readLine();
					readBook[5] = reader.readLine();
					readBook[6] = reader.readLine();
				}

				// booklist[count++] = new Book(readBook[0], readBook[1], Integer.parseInt(readBook[2]), readBook[3], readBook[4], readBook[5], readBook[6]); // PART 11 내용 주석
				Book bookitem = new Book(readBook[0], readBook[1], Integer.parseInt(readBook[2]), readBook[3], readBook[4], readBook[5], readBook[6]);
				
				booklist.add(bookitem);

			}

			reader.close(); // BufferedReader 객체 종료
			fr.close(); // FileReader 객체 종료

		} catch (Exception e) {
			System.out.println(e);
		}
	}

	public static void main(String[] args) {
		// String[][] mbook = new String[NUM_BOOK][NUM_ITEM]; // 도서 정보를 저장할 mBook을 2차원
		// 배열로 생성
		// Book[] mBookList = new Book[NUM_BOOK];
		//Book[] mBookList; // 도서 정보를 저장하기 위한 배열  // PART 11 내용 주석
		ArrayList<Book> mBookList;
		int mTotalBook = 0; // 도서 개수를 저장하기 위한 변수
		Scanner input = new Scanner(System.in);

		System.out.print("당신의 이름을 입력하세요 : ");
		String userName = input.next();

		System.out.print("연락처를 입력하세요 : ");
		int userMobile = input.nextInt();

		mUser = new User(userName, userMobile);

		String greeting = "Welcome to Shopping Mall";
		String tagline = "Welcome to Book Market!";

		boolean quit = false; // 종료 여부 설정 변수

		while (!quit) { // quit 변수가 true일 때까지 계속 반복
			System.out.println("***************************************");
			System.out.println("\t" + greeting);
			System.out.println("\t" + tagline);

			/*
			 * 기존 메뉴 설명 주석 처리 System.out.println("***************************************");
			 * System.out.println("1. 고객 정보 확인하기 \t4. 바구니에 항목 추가하기");
			 * System.out.println("2. 장바구니 상품 목록 보기 \t5. 장바구니의 항목 수량 줄이기");
			 * System.out.println("3. 장바구니 비우기 \t6. 장바구니의 항목 삭제하기");
			 * System.out.println("7. 영수증 표시하기 \t8. 종료");
			 * System.out.println("***************************************");
			 */

			menuIntroduction(); // 메뉴 목록 출력 메서드 호출

			try {
				System.out.println("메뉴 번호를 선택해주세요 ");
				int n = input.nextInt();

//		System.out.println(n +"n번을 선택했습니다. ");

				if (n < 1 || n > 9) { // 메뉴 선택 번호가 1~9이 아니면 아래 문자열 출력
					System.out.println("1부터 8까지의 숫자를 입력하세요.");
				}

				else {
					switch (n) { // switch문을 이용하여 메뉴 선택 번호별 정보 출력
					case 1:
						/*
						 * 기존 내용 주석 처리 System.out.println("현재 고객 정보 : "); System.out.println("이름 " +
						 * userName + " 연락처 "+ userMobile); // 메뉴 번호가 1일 때 입력된 고객 이름과 연락처 출력
						 */
						menuGuestInfo(userName, userMobile);
						break;
					case 2:
//				System.out.println("장바구니 상품 목록 보기 : ");
						menuCartItemList();
						break;
					case 3:
//				System.out.println("장바구니 비우기: ");
						menuCartClear();
						break;
					case 4:
//				System.out.println("장바구니에 항목 추가하기 : ");
						// menuCartAddItem(mbook);
						mTotalBook = totalFileToBookList(); // totalFileToBookList() 호출하여 도서 개수를 mTotalBook에 저장
						// mBookList = new Book[mTotalBook]; // 도서 개수 mTotalBook에 따라 도서 정보를 저장하기 위한 배열 mBookList 초기화 // PART 11 내용 주석
						mBookList = new ArrayList<Book>();
						System.out.println("mTotalbook : "+ mTotalBook);
						menuCartAddItem(mBookList);
						break;
					case 5:
//				System.out.println("5. 장바구니의 항목 수량 줄이기");
						menuCartRemoveItemCount();
						break;
					case 6:
//				System.out.println("6. 장바구니의 항목 삭제하기");
						menuCartRemoveItem();
						break;
					case 7:
//				System.out.println("7. 영수증 표시하기");
						menuCartBill();
						break;
					case 8:
//				System.out.println("8. 종료");
						menuExit();
						quit = true; // quit에 true를 넣어 반복문 종료 조건을 충족
						break;
					case 9:
						menuAdminLogin();
						break;
					}
				}
			} catch (CartException e) {
				System.out.println(e.getMessage());
				//quit = true;
			}

			catch (Exception e) {
				System.out.println("올바르지 않은 메뉴 선택으로 종료합니다.");
				quit = true;
			}
		}
	}
}

 

'한빛아카데미 - JAVA 마스터' 교재의 프로젝트 내용입니다.


프로젝트 구조도

 

PART11 도서 정보 파일 저장 및 읽어오기

클래스 Welcome - 수정 및 추가

- BookList(), menuCartAddItem(), menuAdminLogin() 수정

- totalFileToBookList(), setFileToBookList() 추가

 

package com.market.main;

import java.util.Scanner;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.market.bookitem.Book; // Book 클래스 사용하기 위한 선언
import com.market.cart.Cart; // Cart 클래스 사용하기 위한 선언
import com.market.member.Admin; // Admin 클래스 사용하기 위한 선언
import com.market.member.User; // User 클래스 사용하기 위한 선언
import com.market.exception.CartException; // CartException 사용하기 위한 선언

public class Welcome {
	static final int NUM_BOOK = 3; // 도서의 개수에 대한 상수 NUM_BOOK 선언
	static final int NUM_ITEM = 7; // 도서 정보의 개수에 대한 상수 NUM_ITEM 선언
	// static CartItem[] mCartItem = new CartItem[NUM_BOOK];
	// static int mCartCount = 0;
	static Cart mCart = new Cart(); // Cart 클래스를 사용하기 위한 객체 생성
	static User mUser;

	public static void menuIntroduction() { // 메뉴 출력하는 메서드
		System.out.println("***************************************");
		System.out.println(" 1. 고객 정보 확인하기 \t4. 바구니에 항목 추가하기");
		System.out.println(" 2. 장바구니 상품 목록 보기 \t5. 장바구니의 항목 수량 줄이기");
		System.out.println(" 3. 장바구니 비우기 \t6. 장바구니의 항목 삭제하기");
		System.out.println(" 7. 영수증 표시하기 \t8. 종료");
		System.out.println(" 9. 관리자 로그인");
		System.out.println("***************************************");
	}

	public static void menuGuestInfo(String name, int mobile) { // 고객 정보 확인하는 메서드
		System.out.println("현재 고객 정보 : ");
		System.out.println("이름 " + mUser.getName() + " 연락처 " + mUser.getPhone());

		// System.out.println("이름 " + name + " 연락처 " + mobile);
		// Person person = new Person(name, mobile);
		// System.out.println("이름 " + person.getName() + " 연락처 " + person.getPhone());
	}

	public static void menuCartItemList() { // 장바구니 상품 목록 확인하는 메서드
		/*
		 * System.out.println("장바구니 상품 목록 :");
		 * System.out.println("-----------------------------------------------");
		 * System.out.println("       도서ID \t|     수 량 \t|       합 계"); for(int i = 0; i
		 * < mCartCount; i++) { System.out.print("     "+mCartItem[i].getBookID() +
		 * "\t| "); System.out.print("     "+mCartItem[i].getQuantity() + "\t| ");
		 * System.out.println("     "+mCartItem[i].getTotalPrice()); }
		 * System.out.println("-----------------------------------------------");
		 */

		if (mCart.mCartCount >= 0) {
			mCart.printCart();
		}
	}

	public static void menuCartClear() throws CartException { // 장바구니 모든 항목 삭제하는 메서드
		// System.out.println("장바구니 비우기: ");
		if (mCart.mCartCount == 0) {
			throw new CartException("장바구니에 항목이 없습니다");
			// System.out.println("장바구니에 항목이 없습니다");
		} else {
			System.out.println("장바구니의 모든 항목을 삭제하겠습니까? Y | N ");
			Scanner input = new Scanner(System.in);
			String str = input.nextLine();

			if (str.toUpperCase().equals("Y")) {
				mCart.deleteBook();
			}

		}
	}

	public static void menuCartAddItem(Book[] booklist) { // String[][] book -> Book[] booklist 변경 매개변수 추가, 장바구니에 도서를
															// 추가하는 메서드
		// System.out.println("장바구니에 항목 추가하기 : ");

		// BookList(book); // 도서 정보를 저장하는 메서드 호출
		BookList(booklist);
		/*
		 * for (int i = 0; i < NUM_BOOK; i++) { // 도서 정보 출력 for (int j = 0; j <
		 * NUM_ITEM; j++) System.out.print(book[i][j] + " | "); System.out.println("");
		 * }
		 */
		mCart.printBookList(booklist);
		
		boolean quit = false;

		while (!quit) { // 장바구니에 항목을 추가하지 않을 때까지 반복하는 while문
			System.out.print("장바구니에 추가할 도서의 ID를 입력하세요 : ");

			Scanner input = new Scanner(System.in);
			String str = input.nextLine(); // 도서의 ID를 입력받음

			boolean flag = false;
			int numId = -1;

			for (int i = 0; i < NUM_BOOK; i++) { // 입력된 도서의 ID와 저장되어 있는 도서 정보의 ID가 일치하는지 확인하여
				if (str.equals(booklist[i].getBookId())) { // 일치하면 도서 정보의 numId(인덱스 번호)와 flag(일치 여부) 변수에 값을 변경하여 저장하고
															// 반복문 종료
					numId = i;
					flag = true;
					break;
				}
			}

			if (flag) { // 변수 flag가 참이면(입력된 도서의 ID와 저장되어 있는 도서 정보의 ID가 일치하면) 반복문을 종료하고, 거짓이면 '다시 입력해
						// 주세요' 출력
				System.out.println("장바구니에 추가하겠습니까? Y | N");
				str = input.nextLine(); // 장바구니에 도서 추가 여부를 위한 입력값을 받음

				if (str.toUpperCase().equals("Y")) { // 입력값을 대문자로 변경하여 Y이면 '도서가 장바구니에 추가되었습니다.' 출력
					System.out.println(booklist[numId].getBookId() + "도서가 장바구니에 추가되었습니다.");

					// 장바구니에 넣기
					if (!isCartInBook(booklist[numId].getBookId()))
						mCart.insertBook(booklist[numId]);
				}

				quit = true;

			} else
				System.out.println("다시 입력해 주세요");
		}
	}

	public static boolean isCartInBook(String bookId) { // 장바구니에 담긴 도서의 ID와 장바구니에 담을 도서의 ID를 비교하는 메서드
		/*
		 * boolean flag = false; for(int i = 0; i < mCartCount; i++) { if(bookId ==
		 * mCartItem[i].getBookID()) {
		 * mCartItem[i].setQuantity(mCartItem[i].getQuantity()+1); flag = true; } }
		 * return flag;
		 */
		return mCart.isCartInBook(bookId);
	}

	public static void menuCartRemoveItemCount() { // 장바구니의 항목 수량 줄이는 메서드
		System.out.println("5. 장바구니의 항목 수량 줄이기");
	}

	public static void menuCartRemoveItem() throws CartException { // 장바구니의 항목 삭제하는 메서드
		// System.out.println("6. 장바구니의 항목 삭제하기");
		if (mCart.mCartCount == 0)
			throw new CartException("장바구니에 항목이 없습니다");
		// System.out.println("장바구니에 항목이 없습니다");
		else {
			menuCartItemList();
			boolean quit = false;
			while (!quit) {
				System.out.print("장바구니에서 삭제할 도서의 ID를 입력하세요 :");
				Scanner input = new Scanner(System.in);
				String str = input.nextLine();
				boolean flag = false;
				int numId = -1;

				for (int i = 0; i < mCart.mCartCount; i++) {
					if (str.equals(mCart.mCartItem[i].getBookID())) {
						numId = i;
						flag = true;
						break;
					}
				}

				if (flag) {
					System.out.println("장바구니의 항목을 삭제하시겠습니까? Y | N ");
					str = input.nextLine();
					if (str.toUpperCase().equals("Y")) {
						System.out.println(mCart.mCartItem[numId].getBookID() + "도서가 삭제되었습니다.");
						mCart.removeCart(numId); // Cart 클래스의 구현된 removeCart 메서드로 도서 삭제 진행
					}
					quit = true;
				} else
					System.out.println("다시 입력해 주세요");
			}
		}
	}

	public static void menuCartBill() throws CartException { // 주문 처리를 위한 고객의 정보 저장하는 메서드
		// System.out.println("7. 영수증 표시하기");
		if (mCart.mCartCount == 0)
			throw new CartException("장바구니에 항목이 없습니다");
		// System.out.println("장바구니에 항목이 없습니다.");

		else {
			System.out.println("배송받을 분은 고객 정보와 같습니까? Y | N ");
			Scanner input = new Scanner(System.in);
			String str = input.nextLine();

			if (str.toUpperCase().equals("Y")) {
				System.out.println("배송지를 입력해주세요 ");
				String address = input.nextLine();
				printBill(mUser.getName(), String.valueOf(mUser.getPhone()), address); // 배송을 위한 고객정보와 영수증 출력을 위한
																						// printBill 메서드 호출
			} else {
				System.out.print("배송받을 고객명을 입력하세요 ");
				String name = input.nextLine();
				System.out.print("배송받을 고객의 연락처를 입력하세요 ");
				String phone = input.nextLine();
				System.out.print("배송받을 고객의 배송지를 입력해주세요 ");
				String address = input.nextLine();
				printBill(name, phone, address);
			}
		}
	}

	public static void printBill(String name, String phone, String address) { // 주문 처리 후 영수증을 표시하는 메서드
		Date date = new Date(); // MM/dd/yyyy 형식의 현재 날짜 정보를 엳음
		SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
		String strDate = formatter.format(date);
		System.out.println();
		System.out.println("----------------배송받을 고객 정보-----------------");
		System.out.println("고객명 : " + name + "   \t\t연락처 : " + phone);
		System.out.println("배송지 : " + address + "   \t\t발송일 : " + strDate);

		mCart.printCart(); // 장바구니에 담긴 항목 출력

		int sum = 0;
		for (int i = 0; i < mCart.mCartCount; i++)
			sum += mCart.mCartItem[i].getTotalPrice();

		System.out.println("\t\t\t주문 총금액 : " + sum + "원\n");
		System.out.println("-----------------------------------------------");
		System.out.println();
	}

	public static void menuExit() { // 종료하는 메서드
		System.out.println("8. 종료");
	}

	public static void menuAdminLogin() { // 관리자 로그인 메서드
		System.out.println("관리자 정보를 입력하세요");

		Scanner input = new Scanner(System.in);
		System.out.print("아이디: ");
		String adminId = input.next();

		System.out.print("비밀번호: ");
		String adminPW = input.next();

		Admin admin = new Admin(mUser.getName(), mUser.getPhone());
		if (adminId.equals(admin.getId()) && adminPW.equals(admin.getPassword())) {
			String[] writeBook = new String[7];
			System.out.println("도서 정보를 추가하겠습니까? Y | N " );
			String str = input.next();
			
			if(str.toUpperCase().equals("Y")) {
				Date date = new Date();
				SimpleDateFormat formatter = new SimpleDateFormat("yyMMddhhmmss");
				String strDate = formatter.format(date);
				writeBook[0] = "ISBN" + strDate;
				System.out.println("도서ID : " + writeBook[0]);
				String st1 = input.nextLine(); // 키보드로 한 행 입력시 엔터키를 입력으로 처리
				System.out.print("도서명 : ");
				writeBook[1] = input.nextLine();
				System.out.print("가격 : ");
				writeBook[2] = input.nextLine();
				System.out.print("저자 : ");
				writeBook[3] = input.nextLine();
				System.out.print("설명 : ");
				writeBook[4] = input.nextLine();
				System.out.print("분야 : ");
				writeBook[5] = input.nextLine();
				System.out.print("출판일 : ");
				writeBook[6] = input.nextLine();
				
				try { // 파일 처리를 위한 try ~ catch 문
					FileWriter fw = new FileWriter("book.txt", true); // book.txt 파일에 쓰기 위해 FileWriter 객체 생성
																	  // 기존 파일에 쓰기 위해 FileWriter 생성자에 true 작성
					
					for(int i = 0; i < 7; i++) { // 새로 입력받은 도서정보를 book.txt 파일에 저장
						fw.write(writeBook[i]+"\n");
					}
					
					fw.close(); // FileWriter 객체 종료
					System.out.println("새 도서 정보가 저장되었습니다.");
					
				} catch(Exception e) {
					System.out.println(e);
				}
			}else {
				System.out.println("이름 " + admin.getName() + " 연락처 " + admin.getPhone());
				System.out.println("아이디 " + admin.getId() + " 비밀번호 " + admin.getPassword());
			}

		} else
			System.out.println("관리자 정보가 일치하지 않습니다.");
	}

	public static void BookList(Book[] booklist) { // 도서 정보를 저장하는 메서드
		setFileToBookList(booklist);
		/*
		 * booklist[0] = new Book("ISBN1234", "쉽게 배우는 JSP 웹 프로그래밍", 27000);
		 * booklist[0].setAuthor("송미영");
		 * booklist[0].setDescription("단계별로 쇼핑몰을 구현하며 배우는 JSP 웹 프로그래밍");
		 * booklist[0].setCategory("IT전문서");
		 * booklist[0].setReleaseDate("2018/10/08");
		 * 
		 * booklist[1] = new Book("ISBN1235", "안드로이드 프로그래밍", 33000);
		 * booklist[1].setAuthor("우재남");
		 * booklist[1].setDescription("실습 단계별 명쾌한 멘토링!");
		 * booklist[1].setCategory("IT전문서");
		 * booklist[1].setReleaseDate("2022/01/22");
		 *
		 * booklist[2] = new Book("ISBN1236", "스크래치", 22000);
		 * booklist[2].setAuthor("고광일");
		 * booklist[2].setDescription("컴퓨팅 사고력을 키우는 블록 코딩");
		 * booklist[2].setCategory("컴퓨터입문");
		 * booklist[2].setReleaseDate("2019/06/10");
		 */

		/*
		 * book[0][0] = "ISBN1234";
		 * book[0][1] = "쉽게 배우는 JSP 웹 프로그래밍";
		 * book[0][2] = "27000"; // 27,000 
		 * book[0][3] = "송미영";
		 * book[0][4] = "단계별로 쇼핑몰을 구현하며 배우는 JSP 웹 프로그래밍 ";
		 * book[0][5] = "IT전문서";
		 * book[0][6] = "2018/10/08";
		 * book[1][0] = "ISBN1235";
		 * book[1][1] = "안드로이드 프로그래밍";
		 * book[1][2] = "33000"; // 33,000
		 * book[1][3] = "우재남";
		 * book[1][4] = "실습 단계별 명쾌한 멘토링!";
		 * book[1][5] = "IT전문서";
		 * book[1][6] = "2022/01/22";
		 * book[2][0] = "ISBN1236";
		 * book[2][1] = "스크래치";
		 * book[2][2] = "22000"; // 22,000
		 * book[2][3] = "고광일";
		 * book[2][4] = "컴퓨팅 사고력을 키우는 블록 코딩";
		 * book[2][5] = "컴퓨터입문";
		 * book[2][6] = "2019/06/10";
		 */
	}

	public static int totalFileToBookList() { // 파일에서 도서의 개수를 얻는 메서드
		try {
			FileReader fr = new FileReader("book.txt"); // book.txt 파일을 읽기 위한 FileReder 객체 생성
			BufferedReader reader = new BufferedReader(fr); // 파일에서 한 행씩 읽기 위한 BufferedReader 객체 생성

			String str;
			int num = 0;
			while ((str = reader.readLine()) != null) { // 파일에서 읽을 행이 없을 때 까지 반복
				if (str.contains("ISBN")) // 파일에서 읽은 한 행에 문자열 "ISBN"이 포함되어 있으면 도서의 개수 num을 1 증가시킴
					++num;
			}

			reader.close(); // BufferedReader 객체 종료
			fr.close(); // FileReader 객체 종료
			return num;
		} catch (Exception e) {
			System.out.println(e);
		}
		return 0;
	}

	public static void setFileToBookList(Book[] booklist) { // 파일에서 도서 정보 목록을 읽어 저장하는 매서드
		try {
			FileReader fr = new FileReader("book.txt"); // book.txt 파일을 읽기 위한 FileReder 객체 생성
			BufferedReader reader = new BufferedReader(fr); // 파일에서 한 행씩 읽기 위한 BufferedReader 객체 생성

			String str2;
			String[] readBook = new String[7];
			int count = 0;

			while ((str2 = reader.readLine()) != null) { // 파일에서 읽을 행이 없을 때까지 반복
				if (str2.contains("ISBN")) { // 파일에서 읽은 한 행에 문자열 "ISBN"이 포함되어 있으면 도서 정보에 대해 한 행씩 읽어 지역변수 readBook에 저장
					readBook[0] = str2;
					readBook[1] = reader.readLine();
					readBook[2] = reader.readLine();
					readBook[3] = reader.readLine();
					readBook[4] = reader.readLine();
					readBook[5] = reader.readLine();
					readBook[6] = reader.readLine();
				}

				booklist[count++] = new Book(readBook[0], readBook[1], Integer.parseInt(readBook[2]), readBook[3],
						readBook[4], readBook[5], readBook[6]);
			}

			reader.close(); // BufferedReader 객체 종료
			fr.close(); // FileReader 객체 종료

		} catch (Exception e) {
			System.out.println(e);
		}
	}

	public static void main(String[] args) {
		// String[][] mbook = new String[NUM_BOOK][NUM_ITEM]; // 도서 정보를 저장할 mBook을 2차원
		// 배열로 생성
		// Book[] mBookList = new Book[NUM_BOOK];
		Book[] mBookList; // 도서 정보를 저장하기 위한 배열
		int mTotalBook = 0; // 도서 개수를 저장하기 위한 변수
		Scanner input = new Scanner(System.in);

		System.out.print("당신의 이름을 입력하세요 : ");
		String userName = input.next();

		System.out.print("연락처를 입력하세요 : ");
		int userMobile = input.nextInt();

		mUser = new User(userName, userMobile);

		String greeting = "Welcome to Shopping Mall";
		String tagline = "Welcome to Book Market!";

		boolean quit = false; // 종료 여부 설정 변수

		while (!quit) { // quit 변수가 true일 때까지 계속 반복
			System.out.println("***************************************");
			System.out.println("\t" + greeting);
			System.out.println("\t" + tagline);

			/*
			 * 기존 메뉴 설명 주석 처리 System.out.println("***************************************");
			 * System.out.println("1. 고객 정보 확인하기 \t4. 바구니에 항목 추가하기");
			 * System.out.println("2. 장바구니 상품 목록 보기 \t5. 장바구니의 항목 수량 줄이기");
			 * System.out.println("3. 장바구니 비우기 \t6. 장바구니의 항목 삭제하기");
			 * System.out.println("7. 영수증 표시하기 \t8. 종료");
			 * System.out.println("***************************************");
			 */

			menuIntroduction(); // 메뉴 목록 출력 메서드 호출

			try {
				System.out.println("메뉴 번호를 선택해주세요 ");
				int n = input.nextInt();

//		System.out.println(n +"n번을 선택했습니다. ");

				if (n < 1 || n > 9) { // 메뉴 선택 번호가 1~9이 아니면 아래 문자열 출력
					System.out.println("1부터 8까지의 숫자를 입력하세요.");
				}

				else {
					switch (n) { // switch문을 이용하여 메뉴 선택 번호별 정보 출력
					case 1:
						/*
						 * 기존 내용 주석 처리 System.out.println("현재 고객 정보 : "); System.out.println("이름 " +
						 * userName + " 연락처 "+ userMobile); // 메뉴 번호가 1일 때 입력된 고객 이름과 연락처 출력
						 */
						menuGuestInfo(userName, userMobile);
						break;
					case 2:
//				System.out.println("장바구니 상품 목록 보기 : ");
						menuCartItemList();
						break;
					case 3:
//				System.out.println("장바구니 비우기: ");
						menuCartClear();
						break;
					case 4:
//				System.out.println("장바구니에 항목 추가하기 : ");
						// menuCartAddItem(mbook);
						mTotalBook = totalFileToBookList(); // totalFileToBookList() 호출하여 도서 개수를 mTotalBook에 저장
						mBookList = new Book[mTotalBook]; // 도서 개수 mTotalBook에 따라 도서 정보를 저장하기 위한 배열 mBookList 초기화
						System.out.println("mTotalbook : "+ mTotalBook);
						menuCartAddItem(mBookList);
						break;
					case 5:
//				System.out.println("5. 장바구니의 항목 수량 줄이기");
						menuCartRemoveItemCount();
						break;
					case 6:
//				System.out.println("6. 장바구니의 항목 삭제하기");
						menuCartRemoveItem();
						break;
					case 7:
//				System.out.println("7. 영수증 표시하기");
						menuCartBill();
						break;
					case 8:
//				System.out.println("8. 종료");
						menuExit();
						quit = true; // quit에 true를 넣어 반복문 종료 조건을 충족
						break;
					case 9:
						menuAdminLogin();
						break;
					}
				}
			} catch (CartException e) {
				System.out.println(e.getMessage());
				//quit = true;
			}

			catch (Exception e) {
				System.out.println("올바르지 않은 메뉴 선택으로 종료합니다.");
				quit = true;
			}
		}
	}
}

 

'한빛아카데미 - JAVA 마스터' 교재의 프로젝트 내용입니다.


프로젝트 구조도

 

PART10 메뉴 선택 및 장바구니 예외 처리하기

com/market.exception 패키지 생성

- CartException 클래스 생성

 

package com.market.exception;

public class CartException extends Exception {
	public CartException(String str) {
		super(str);
	}
}

 

클래스 Welcome - 수정

package com.market.main;

import java.util.Scanner;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.market.bookitem.Book; // Book 클래스 사용하기 위한 선언
import com.market.cart.Cart; // Cart 클래스 사용하기 위한 선언
import com.market.member.Admin; // Admin 클래스 사용하기 위한 선언
import com.market.member.User; // User 클래스 사용하기 위한 선언
import com.market.exception.CartException; // CartException 사용하기 위한 선언

public class Welcome {
	static final int NUM_BOOK = 3; // 도서의 개수에 대한 상수 NUM_BOOK 선언
	static final int NUM_ITEM = 7; // 도서 정보의 개수에 대한 상수 NUM_ITEM 선언
	// static CartItem[] mCartItem = new CartItem[NUM_BOOK];
	// static int mCartCount = 0;
	static Cart mCart = new Cart(); // Cart 클래스를 사용하기 위한 객체 생성
	static User mUser;

	public static void menuIntroduction() { // 메뉴 출력하는 메서드
		System.out.println("***************************************");
		System.out.println(" 1. 고객 정보 확인하기 \t4. 바구니에 항목 추가하기");
		System.out.println(" 2. 장바구니 상품 목록 보기 \t5. 장바구니의 항목 수량 줄이기");
		System.out.println(" 3. 장바구니 비우기 \t6. 장바구니의 항목 삭제하기");
		System.out.println(" 7. 영수증 표시하기 \t8. 종료");
		System.out.println(" 9. 관리자 로그인");
		System.out.println("***************************************");
	}

	public static void menuGuestInfo(String name, int mobile) { // 고객 정보 확인하는 메서드
		System.out.println("현재 고객 정보 : ");
		System.out.println("이름 " + mUser.getName() + " 연락처 " + mUser.getPhone());

		// System.out.println("이름 " + name + " 연락처 " + mobile);
		// Person person = new Person(name, mobile);
		// System.out.println("이름 " + person.getName() + " 연락처 " + person.getPhone());
	}

	public static void menuCartItemList() { // 장바구니 상품 목록 확인하는 메서드
		/*
		 * System.out.println("장바구니 상품 목록 :");
		 * System.out.println("-----------------------------------------------");
		 * System.out.println("       도서ID \t|     수 량 \t|       합 계"); for(int i = 0; i
		 * < mCartCount; i++) { System.out.print("     "+mCartItem[i].getBookID() +
		 * "\t| "); System.out.print("     "+mCartItem[i].getQuantity() + "\t| ");
		 * System.out.println("     "+mCartItem[i].getTotalPrice()); }
		 * System.out.println("-----------------------------------------------");
		 */

		if (mCart.mCartCount >= 0) {
			mCart.printCart();
		}
	}

	public static void menuCartClear() throws CartException { // 장바구니 모든 항목 삭제하는 메서드
		// System.out.println("장바구니 비우기: ");
		if (mCart.mCartCount == 0) {
			throw new CartException("장바구니에 항목이 없습니다");
			//System.out.println("장바구니에 항목이 없습니다");
		} else {
			System.out.println("장바구니의 모든 항목을 삭제하겠습니까? Y | N ");
			Scanner input = new Scanner(System.in);
			String str = input.nextLine();

			if (str.toUpperCase().equals("Y")) {
				mCart.deleteBook();
			}

		}
	}

	public static void menuCartAddItem(Book[] booklist) { // String[][] book -> Book[] booklist 변경 매개변수 추가, 장바구니에 도서를
															// 추가하는 메서드
		// System.out.println("장바구니에 항목 추가하기 : ");

		// BookList(book); // 도서 정보를 저장하는 메서드 호출
		BookList(booklist);
		/*
		 * for (int i = 0; i < NUM_BOOK; i++) { // 도서 정보 출력 for (int j = 0; j <
		 * NUM_ITEM; j++) System.out.print(book[i][j] + " | "); System.out.println("");
		 * }
		 */
		mCart.printBookList(booklist);

		boolean quit = false;

		while (!quit) { // 장바구니에 항목을 추가하지 않을 때까지 반복하는 while문
			System.out.print("장바구니에 추가할 도서의 ID를 입력하세요 : ");

			Scanner input = new Scanner(System.in);
			String str = input.nextLine(); // 도서의 ID를 입력받음

			boolean flag = false;
			int numId = -1;

			for (int i = 0; i < NUM_BOOK; i++) { // 입력된 도서의 ID와 저장되어 있는 도서 정보의 ID가 일치하는지 확인하여
				if (str.equals(booklist[i].getBookId())) { // 일치하면 도서 정보의 numId(인덱스 번호)와 flag(일치 여부) 변수에 값을 변경하여 저장하고
															// 반복문 종료
					numId = i;
					flag = true;
					break;
				}
			}

			if (flag) { // 변수 flag가 참이면(입력된 도서의 ID와 저장되어 있는 도서 정보의 ID가 일치하면) 반복문을 종료하고, 거짓이면 '다시 입력해
						// 주세요' 출력
				System.out.println("장바구니에 추가하겠습니까? Y | N");
				str = input.nextLine(); // 장바구니에 도서 추가 여부를 위한 입력값을 받음

				if (str.toUpperCase().equals("Y")) { // 입력값을 대문자로 변경하여 Y이면 '도서가 장바구니에 추가되었습니다.' 출력
					System.out.println(booklist[numId].getBookId() + "도서가 장바구니에 추가되었습니다.");

					// 장바구니에 넣기
					if (!isCartInBook(booklist[numId].getBookId()))
						mCart.insertBook(booklist[numId]);
				}

				quit = true;

			} else
				System.out.println("다시 입력해 주세요");
		}
	}

	public static boolean isCartInBook(String bookId) { // 장바구니에 담긴 도서의 ID와 장바구니에 담을 도서의 ID를 비교하는 메서드
		/*
		 * boolean flag = false; for(int i = 0; i < mCartCount; i++) { if(bookId ==
		 * mCartItem[i].getBookID()) {
		 * mCartItem[i].setQuantity(mCartItem[i].getQuantity()+1); flag = true; } }
		 * return flag;
		 */
		return mCart.isCartInBook(bookId);
	}

	public static void menuCartRemoveItemCount() { // 장바구니의 항목 수량 줄이는 메서드
		System.out.println("5. 장바구니의 항목 수량 줄이기");
	}

	public static void menuCartRemoveItem()  throws CartException { // 장바구니의 항목 삭제하는 메서드
		// System.out.println("6. 장바구니의 항목 삭제하기");
		if (mCart.mCartCount == 0)
			throw new CartException("장바구니에 항목이 없습니다");
			// System.out.println("장바구니에 항목이 없습니다");
		else {
			menuCartItemList();
			boolean quit = false;
			while (!quit) {
				System.out.print("장바구니에서 삭제할 도서의 ID를 입력하세요 :");
				Scanner input = new Scanner(System.in);
				String str = input.nextLine();
				boolean flag = false;
				int numId = -1;

				for (int i = 0; i < mCart.mCartCount; i++) {
					if (str.equals(mCart.mCartItem[i].getBookID())) {
						numId = i;
						flag = true;
						break;
					}
				}

				if (flag) {
					System.out.println("장바구니의 항목을 삭제하시겠습니까? Y | N ");
					str = input.nextLine();
					if (str.toUpperCase().equals("Y")) {
						System.out.println(mCart.mCartItem[numId].getBookID() + "도서가 삭제되었습니다.");
						mCart.removeCart(numId); // Cart 클래스의 구현된 removeCart 메서드로 도서 삭제 진행
					}
					quit = true;
				} else
					System.out.println("다시 입력해 주세요");
			}
		}
	}

	public static void menuCartBill() throws CartException{ // 주문 처리를 위한 고객의 정보 저장하는 메서드
		// System.out.println("7. 영수증 표시하기");
		if (mCart.mCartCount == 0)
			throw new CartException("장바구니에 항목이 없습니다");
			//System.out.println("장바구니에 항목이 없습니다.");

		else {
			System.out.println("배송받을 분은 고객 정보와 같습니까? Y | N ");
			Scanner input = new Scanner(System.in);
			String str = input.nextLine();

			if (str.toUpperCase().equals("Y")) {
				System.out.println("배송지를 입력해주세요 ");
				String address = input.nextLine();
				printBill(mUser.getName(), String.valueOf(mUser.getPhone()), address); // 배송을 위한 고객정보와 영수증 출력을 위한
																						// printBill 메서드 호출
			} else {
				System.out.print("배송받을 고객명을 입력하세요 ");
				String name = input.nextLine();
				System.out.print("배송받을 고객의 연락처를 입력하세요 ");
				String phone = input.nextLine();
				System.out.print("배송받을 고객의 배송지를 입력해주세요 ");
				String address = input.nextLine();
				printBill(name, phone, address);
			}
		}
	}

	public static void printBill(String name, String phone, String address) { // 주문 처리 후 영수증을 표시하는 메서드
		Date date = new Date(); // MM/dd/yyyy 형식의 현재 날짜 정보를 엳음
		SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
		String strDate = formatter.format(date);
		System.out.println();
		System.out.println("----------------배송받을 고객 정보-----------------");
		System.out.println("고객명 : " + name + "   \t\t연락처 : " + phone);
		System.out.println("배송지 : " + address + "   \t\t발송일 : " + strDate);

		mCart.printCart(); // 장바구니에 담긴 항목 출력

		int sum = 0;
		for (int i = 0; i < mCart.mCartCount; i++)
			sum += mCart.mCartItem[i].getTotalPrice();

		System.out.println("\t\t\t주문 총금액 : " + sum + "원\n");
		System.out.println("-----------------------------------------------");
		System.out.println();
	}

	public static void menuExit() { // 종료하는 메서드
		System.out.println("8. 종료");
	}

	public static void menuAdminLogin() { // 관리자 로그인 메서드
		System.out.println("관리자 정보를 입력하세요");

		Scanner input = new Scanner(System.in);
		System.out.print("아이디: ");
		String adminId = input.next();

		System.out.print("비밀번호: ");
		String adminPW = input.next();

		Admin admin = new Admin(mUser.getName(), mUser.getPhone());
		if (adminId.equals(admin.getId()) && adminPW.equals(admin.getPassword())) {
			System.out.println("이름 " + admin.getName() + " 연락처 " + admin.getPhone());
			System.out.println("아이디 " + admin.getId() + " 비밀번호 " + admin.getPassword());
		} else
			System.out.println("관리자 정보가 일치하지 않습니다.");
	}

	public static void BookList(Book[] booklist) { // 도서 정보를 저장하는 메서드

		booklist[0] = new Book("ISBN1234", "쉽게 배우는 JSP 웹 프로그래밍", 27000);
		booklist[0].setAuthor("송미영");
		booklist[0].setDescription("단계별로 쇼핑몰을 구현하며 배우는 JSP 웹 프로그래밍");
		booklist[0].setCategory("IT전문서");
		booklist[0].setReleaseDate("2018/10/08");

		booklist[1] = new Book("ISBN1235", "안드로이드 프로그래밍", 33000);
		booklist[1].setAuthor("우재남");
		booklist[1].setDescription("실습 단계별 명쾌한 멘토링!");
		booklist[1].setCategory("IT전문서");
		booklist[1].setReleaseDate("2022/01/22");

		booklist[2] = new Book("ISBN1236", "스크래치", 22000);
		booklist[2].setAuthor("고광일");
		booklist[2].setDescription("컴퓨팅 사고력을 키우는 블록 코딩");
		booklist[2].setCategory("컴퓨터입문");
		booklist[2].setReleaseDate("2019/06/10");

		/*
		 * book[0][0] = "ISBN1234"; book[0][1] = "쉽게 배우는 JSP 웹 프로그래밍"; book[0][2] =
		 * "27000"; // 27,000 book[0][3] = "송미영"; book[0][4] =
		 * "단계별로 쇼핑몰을 구현하며 배우는 JSP 웹 프로그래밍 "; book[0][5] = "IT전문서"; book[0][6] =
		 * "2018/10/08";
		 * 
		 * book[1][0] = "ISBN1235"; book[1][1] = "안드로이드 프로그래밍"; book[1][2] = "33000"; //
		 * 33,000 book[1][3] = "우재남"; book[1][4] = "실습 단계별 명쾌한 멘토링!"; book[1][5] =
		 * "IT전문서"; book[1][6] = "2022/01/22";
		 * 
		 * book[2][0] = "ISBN1236"; book[2][1] = "스크래치"; book[2][2] = "22000"; // 22,000
		 * book[2][3] = "고광일"; book[2][4] = "컴퓨팅 사고력을 키우는 블록 코딩"; book[2][5] = "컴퓨터입문";
		 * book[2][6] = "2019/06/10";
		 */
	}

	public static void main(String[] args) {
		// String[][] mbook = new String[NUM_BOOK][NUM_ITEM]; // 도서 정보를 저장할 mBook을 2차원
		// 배열로 생성
		Book[] mBookList = new Book[NUM_BOOK];
		Scanner input = new Scanner(System.in);

		System.out.print("당신의 이름을 입력하세요 : ");
		String userName = input.next();

		System.out.print("연락처를 입력하세요 : ");
		int userMobile = input.nextInt();

		mUser = new User(userName, userMobile);

		String greeting = "Welcome to Shopping Mall";
		String tagline = "Welcome to Book Market!";

		boolean quit = false; // 종료 여부 설정 변수

		while (!quit) { // quit 변수가 true일 때까지 계속 반복
			System.out.println("***************************************");
			System.out.println("\t" + greeting);
			System.out.println("\t" + tagline);

			/*
			 * 기존 메뉴 설명 주석 처리 System.out.println("***************************************");
			 * System.out.println("1. 고객 정보 확인하기 \t4. 바구니에 항목 추가하기");
			 * System.out.println("2. 장바구니 상품 목록 보기 \t5. 장바구니의 항목 수량 줄이기");
			 * System.out.println("3. 장바구니 비우기 \t6. 장바구니의 항목 삭제하기");
			 * System.out.println("7. 영수증 표시하기 \t8. 종료");
			 * System.out.println("***************************************");
			 */

			menuIntroduction(); // 메뉴 목록 출력 메서드 호출

			try {
				System.out.println("메뉴 번호를 선택해주세요 ");
				int n = input.nextInt();

//		System.out.println(n +"n번을 선택했습니다. ");

				if (n < 1 || n > 9) { // 메뉴 선택 번호가 1~9이 아니면 아래 문자열 출력
					System.out.println("1부터 8까지의 숫자를 입력하세요.");
				}

				else {
					switch (n) { // switch문을 이용하여 메뉴 선택 번호별 정보 출력
					case 1:
						/*
						 * 기존 내용 주석 처리 System.out.println("현재 고객 정보 : "); System.out.println("이름 " +
						 * userName + " 연락처 "+ userMobile); // 메뉴 번호가 1일 때 입력된 고객 이름과 연락처 출력
						 */
						menuGuestInfo(userName, userMobile);
						break;
					case 2:
//				System.out.println("장바구니 상품 목록 보기 : ");
						menuCartItemList();
						break;
					case 3:
//				System.out.println("장바구니 비우기: ");
						menuCartClear();
						break;
					case 4:
//				System.out.println("장바구니에 항목 추가하기 : ");
						// menuCartAddItem(mbook);
						menuCartAddItem(mBookList);
						break;
					case 5:
//				System.out.println("5. 장바구니의 항목 수량 줄이기");
						menuCartRemoveItemCount();
						break;
					case 6:
//				System.out.println("6. 장바구니의 항목 삭제하기");
						menuCartRemoveItem();
						break;
					case 7:
//				System.out.println("7. 영수증 표시하기");
						menuCartBill();
						break;
					case 8:
//				System.out.println("8. 종료");
						menuExit();
						quit = true; // quit에 true를 넣어 반복문 종료 조건을 충족
						break;
					case 9:
						menuAdminLogin();
						break;
					}
				}
			} catch(CartException e) {
				System.out.println(e.getMessage());
				quit = true;
			}
			
			catch (Exception e) {
				System.out.println("올바르지 않은 메뉴 선택으로 종료합니다.");
				quit = true;
			}
		}
	}
}

'한빛아카데미 - JAVA 마스터' 교재의 프로젝트 내용입니다.


프로젝트 구조도

 

PART9 주문 처리하기

 

패키지 생성

BookMarket 프로젝트

 

com.market.member- Person, User, Admin 클래스

 

com.market.bookitem - Item, Book 클래스

 

com.market.cart - Cart, CartInterface, CartItem 클래스, mCartItem, mCartCount의 접근제한자 public 추가

import com.market.bookitem.Book; // Book 클래스 사용하기 위한 선언 추가
import com.market.bookitem.Book; // Book 클래스 사용하기 위한 선언 추가
import com.market.bookitem.Book; // Book 클래스 사용하기 위한 선언 추가

 

com.market.main - Welcome 클래스

클래스 Welcome - 수정

- menuCartBill() 수정

- printBill() 추가

- import com.market.bookitem.Book; // Book 클래스 사용하기 위한 선언
- import com.market.cart.Cart; // Cart 클래스 사용하기 위한 선언
- import com.market.member.Admin; // Admin 클래스 사용하기 위한 선언
- import com.market.member.User; // User 클래스 사용하기 위한 선언

 

package com.market.main;

import java.util.Scanner;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.market.bookitem.Book; // Book 클래스 사용하기 위한 선언
import com.market.cart.Cart; // Cart 클래스 사용하기 위한 선언
import com.market.member.Admin; // Admin 클래스 사용하기 위한 선언
import com.market.member.User; // User 클래스 사용하기 위한 선언

public class Welcome {
	static final int NUM_BOOK = 3; // 도서의 개수에 대한 상수 NUM_BOOK 선언
	static final int NUM_ITEM = 7; // 도서 정보의 개수에 대한 상수 NUM_ITEM 선언
	// static CartItem[] mCartItem = new CartItem[NUM_BOOK];
	// static int mCartCount = 0;
	static Cart mCart = new Cart(); // Cart 클래스를 사용하기 위한 객체 생성
	static User mUser;

	public static void menuIntroduction() { // 메뉴 출력하는 메서드
		System.out.println("***************************************");
		System.out.println(" 1. 고객 정보 확인하기 \t4. 바구니에 항목 추가하기");
		System.out.println(" 2. 장바구니 상품 목록 보기 \t5. 장바구니의 항목 수량 줄이기");
		System.out.println(" 3. 장바구니 비우기 \t6. 장바구니의 항목 삭제하기");
		System.out.println(" 7. 영수증 표시하기 \t8. 종료");
		System.out.println(" 9. 관리자 로그인");
		System.out.println("***************************************");
	}

	public static void menuGuestInfo(String name, int mobile) { // 고객 정보 확인하는 메서드
		System.out.println("현재 고객 정보 : ");
		System.out.println("이름 "+ mUser.getName() + " 연락처 " + mUser.getPhone());
		
		// System.out.println("이름 " + name + " 연락처 " + mobile);
		// Person person = new Person(name, mobile);
		// System.out.println("이름 " + person.getName() + "   연락처 " + person.getPhone());
	}

	public static void menuCartItemList() { // 장바구니 상품 목록 확인하는 메서드
		/*
		System.out.println("장바구니 상품 목록 :");
		System.out.println("-----------------------------------------------");
		System.out.println("       도서ID \t|     수 량 \t|       합 계");
		for(int i = 0; i < mCartCount; i++) {
			System.out.print("     "+mCartItem[i].getBookID() + "\t| ");
			System.out.print("     "+mCartItem[i].getQuantity() + "\t| ");
			System.out.println("     "+mCartItem[i].getTotalPrice());
		}
		System.out.println("-----------------------------------------------");
		*/
		
		if(mCart.mCartCount >= 0) {
			mCart.printCart();
		}
	}

	public static void menuCartClear() { // 장바구니 모든 항목 삭제하는 메서드
		//System.out.println("장바구니 비우기: ");
		if(mCart.mCartCount == 0) {
			System.out.println("장바구니에 항목이 없습니다");
		}
		else {
			System.out.println("장바구니의 모든 항목을 삭제하겠습니까? Y | N ");
			Scanner input = new Scanner(System.in);
			String str = input.nextLine();
			
			if(str.toUpperCase().equals("Y")) {
				mCart.deleteBook();
			}
			
		}
	}

	public static void menuCartAddItem(Book[] booklist) { // String[][] book -> Book[] booklist 변경 매개변수 추가, 장바구니에 도서를 추가하는 메서드
		// System.out.println("장바구니에 항목 추가하기 : ");

		//BookList(book); // 도서 정보를 저장하는 메서드 호출
		BookList(booklist);
		/*
		for (int i = 0; i < NUM_BOOK; i++) { // 도서 정보 출력
			for (int j = 0; j < NUM_ITEM; j++)
				System.out.print(book[i][j] + " | ");
			System.out.println("");
		}
		*/
		mCart.printBookList(booklist);
		
		boolean quit = false;
		
		while(!quit) { // 장바구니에 항목을 추가하지 않을 때까지 반복하는 while문
			System.out.print("장바구니에 추가할 도서의 ID를 입력하세요 : ");
			
			Scanner input = new Scanner(System.in);
			String str = input.nextLine(); // 도서의 ID를 입력받음
			
			boolean flag = false;
			int numId = -1;
			
			for(int i = 0; i < NUM_BOOK; i++) { // 입력된 도서의 ID와 저장되어 있는 도서 정보의 ID가 일치하는지 확인하여
				if(str.equals(booklist[i].getBookId())) { // 일치하면 도서 정보의 numId(인덱스 번호)와 flag(일치 여부) 변수에 값을 변경하여 저장하고 반복문 종료
					numId = i;
					flag = true;
					break;
				}
			}
			
			if(flag) { // 변수 flag가 참이면(입력된 도서의 ID와 저장되어 있는 도서 정보의 ID가 일치하면) 반복문을 종료하고, 거짓이면 '다시 입력해 주세요' 출력
				System.out.println("장바구니에 추가하겠습니까? Y | N");
				str = input.nextLine(); // 장바구니에 도서 추가 여부를 위한 입력값을 받음
				
				if(str.toUpperCase().equals("Y")) { // 입력값을 대문자로 변경하여 Y이면 '도서가 장바구니에 추가되었습니다.' 출력
					System.out.println(booklist[numId].getBookId() + "도서가 장바구니에 추가되었습니다.");
					
					// 장바구니에 넣기
					if(!isCartInBook(booklist[numId].getBookId()))
							mCart.insertBook(booklist[numId]);
				}
				
				quit = true;
				
			} else
				System.out.println("다시 입력해 주세요");
		}
	}

	public static boolean isCartInBook(String bookId) { // 장바구니에 담긴 도서의 ID와 장바구니에 담을 도서의 ID를 비교하는 메서드
		/*
		boolean flag = false;
		for(int i = 0; i < mCartCount; i++) {
			if(bookId == mCartItem[i].getBookID()) {
				mCartItem[i].setQuantity(mCartItem[i].getQuantity()+1);
				flag = true;
			}
		}
		return flag;
		*/
		return mCart.isCartInBook(bookId);
	}

	public static void menuCartRemoveItemCount() { // 장바구니의 항목 수량 줄이는 메서드
		System.out.println("5. 장바구니의 항목 수량 줄이기");
	}

	public static void menuCartRemoveItem() { // 장바구니의 항목 삭제하는 메서드
		// System.out.println("6. 장바구니의 항목 삭제하기");
		if(mCart.mCartCount == 0)
			System.out.println("장바구니에 항목이 없습니다");
		else {
			menuCartItemList();
			boolean quit = false;
			while(!quit) {
				System.out.print("장바구니에서 삭제할 도서의 ID를 입력하세요 :");
				Scanner input = new Scanner(System.in);
				String str = input.nextLine();
				boolean flag = false;
				int numId = -1;
				
				for(int i = 0; i < mCart.mCartCount; i++) {
					if(str.equals(mCart.mCartItem[i].getBookID())) {
						numId = i;
						flag = true;
						break;
					}
				}
				
				if(flag) {
					System.out.println("장바구니의 항목을 삭제하시겠습니까? Y | N ");
					str = input.nextLine();
					if (str.toUpperCase().equals("Y")) {
						System.out.println(mCart.mCartItem[numId].getBookID() + "도서가 삭제되었습니다.");
						mCart.removeCart(numId); // Cart 클래스의 구현된 removeCart 메서드로 도서 삭제 진행
					}
					quit = true;
				}
				else System.out.println("다시 입력해 주세요");
			}
		}
	}

	public static void menuCartBill() { // 주문 처리를 위한 고객의 정보 저장하는 메서드
		// System.out.println("7. 영수증 표시하기");
		if(mCart.mCartCount == 0) System.out.println("장바구니에 항목이 없습니다.");
		
		else {
			System.out.println("배송받을 분은 고객 정보와 같습니까? Y | N ");
			Scanner input = new Scanner(System.in);
			String str = input.nextLine();
			
			if(str.toUpperCase().equals("Y")) {
				System.out.println("배송지를 입력해주세요 ");
				String address = input.nextLine();
				printBill(mUser.getName(), String.valueOf(mUser.getPhone()), address); // 배송을 위한 고객정보와 영수증 출력을 위한 printBill 메서드 호출
			}
			else {
				System.out.print("배송받을 고객명을 입력하세요 ");
				String name = input.nextLine();
				System.out.print("배송받을 고객의 연락처를 입력하세요 ");
				String phone = input.nextLine();
				System.out.print("배송받을 고객의 배송지를 입력해주세요 ");
				String address = input.nextLine();
				printBill(name, phone, address);
			}
		}
	}
	
	public static void printBill(String name, String phone, String address) {  // 주문 처리 후 영수증을 표시하는 메서드
		Date date = new Date(); // MM/dd/yyyy 형식의 현재 날짜 정보를 엳음
		SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
		String strDate = formatter.format(date);
		System.out.println();
		System.out.println("----------------배송받을 고객 정보-----------------");
		System.out.println("고객명 : "+ name + "   \t\t연락처 : " + phone);
		System.out.println("배송지 : "+ address + "   \t\t발송일 : " + strDate);
		
		mCart.printCart(); // 장바구니에 담긴 항목 출력
		
		int sum = 0;
		for(int i = 0; i < mCart.mCartCount; i++)
			sum += mCart.mCartItem[i].getTotalPrice();
		
		System.out.println("\t\t\t주문 총금액 : " + sum + "원\n");
		System.out.println("-----------------------------------------------");
		System.out.println();
	}

	public static void menuExit() { // 종료하는 메서드
		System.out.println("8. 종료");
	}
	
	public static void menuAdminLogin() {    // 관리자 로그인 메서드
		System.out.println("관리자 정보를 입력하세요");
		
		Scanner input = new Scanner(System.in);
		System.out.print("아이디: ");
		String adminId = input.next();
		
		System.out.print("비밀번호: ");
		String adminPW = input.next();
		
		Admin admin = new Admin(mUser.getName(), mUser.getPhone());
		if(adminId.equals(admin.getId()) && adminPW.equals(admin.getPassword())) {
			System.out.println("이름 "+admin.getName() + " 연락처 " + admin.getPhone());
			System.out.println("아이디 "+admin.getId() + " 비밀번호 "+admin.getPassword());
		}else
			System.out.println("관리자 정보가 일치하지 않습니다.");
	}

	public static void BookList(Book[] booklist) { // 도서 정보를 저장하는 메서드
		
		booklist[0] = new Book("ISBN1234", "쉽게 배우는 JSP 웹 프로그래밍", 27000);
		booklist[0].setAuthor("송미영");
		booklist[0].setDescription("단계별로 쇼핑몰을 구현하며 배우는 JSP 웹 프로그래밍");
		booklist[0].setCategory("IT전문서");
		booklist[0].setReleaseDate("2018/10/08");
		
		booklist[1] = new Book("ISBN1235", "안드로이드 프로그래밍", 33000);
		booklist[1].setAuthor("우재남");
		booklist[1].setDescription("실습 단계별 명쾌한 멘토링!");
		booklist[1].setCategory("IT전문서");
		booklist[1].setReleaseDate("2022/01/22");
		
		booklist[2] = new Book("ISBN1236", "스크래치", 22000);
		booklist[2].setAuthor("고광일");
		booklist[2].setDescription("컴퓨팅 사고력을 키우는 블록 코딩");
		booklist[2].setCategory("컴퓨터입문");
		booklist[2].setReleaseDate("2019/06/10");
		
		/*
		book[0][0] = "ISBN1234";
		book[0][1] = "쉽게 배우는 JSP 웹 프로그래밍";
		book[0][2] = "27000"; // 27,000
		book[0][3] = "송미영";
		book[0][4] = "단계별로 쇼핑몰을 구현하며 배우는 JSP 웹 프로그래밍 ";
		book[0][5] = "IT전문서";
		book[0][6] = "2018/10/08";

		book[1][0] = "ISBN1235";
		book[1][1] = "안드로이드 프로그래밍";
		book[1][2] = "33000"; // 33,000
		book[1][3] = "우재남";
		book[1][4] = "실습 단계별 명쾌한 멘토링!";
		book[1][5] = "IT전문서";
		book[1][6] = "2022/01/22";

		book[2][0] = "ISBN1236";
		book[2][1] = "스크래치";
		book[2][2] = "22000"; // 22,000
		book[2][3] = "고광일";
		book[2][4] = "컴퓨팅 사고력을 키우는 블록 코딩";
		book[2][5] = "컴퓨터입문";
		book[2][6] = "2019/06/10";
		*/
	}

	public static void main(String[] args) {
		// String[][] mbook = new String[NUM_BOOK][NUM_ITEM]; // 도서 정보를 저장할 mBook을 2차원 배열로 생성
		Book[] mBookList = new Book[NUM_BOOK];
		Scanner input = new Scanner(System.in);

		System.out.print("당신의 이름을 입력하세요 : ");
		String userName = input.next();

		System.out.print("연락처를 입력하세요 : ");
		int userMobile = input.nextInt();
		
		mUser = new User(userName, userMobile);

		String greeting = "Welcome to Shopping Mall";
		String tagline = "Welcome to Book Market!";

		boolean quit = false; // 종료 여부 설정 변수

		while (!quit) { // quit 변수가 true일 때까지 계속 반복			
			System.out.println("***************************************");
			System.out.println("\t" + greeting);
			System.out.println("\t" + tagline);

			/*
			 * 기존 메뉴 설명 주석 처리 System.out.println("***************************************");
			 * System.out.println("1. 고객 정보 확인하기 \t4. 바구니에 항목 추가하기");
			 * System.out.println("2. 장바구니 상품 목록 보기 \t5. 장바구니의 항목 수량 줄이기");
			 * System.out.println("3. 장바구니 비우기 \t6. 장바구니의 항목 삭제하기");
			 * System.out.println("7. 영수증 표시하기 \t8. 종료");
			 * System.out.println("***************************************");
			 */

			menuIntroduction(); // 메뉴 목록 출력 메서드 호출

			System.out.println("메뉴 번호를 선택해주세요 ");
			int n = input.nextInt();

//		System.out.println(n +"n번을 선택했습니다. ");

			if (n < 1 || n > 9) { // 메뉴 선택 번호가 1~9이 아니면 아래 문자열 출력
				System.out.println("1부터 8까지의 숫자를 입력하세요.");
			}

			else {
				switch (n) { // switch문을 이용하여 메뉴 선택 번호별 정보 출력
				case 1:
					/*
					 * 기존 내용 주석 처리 
					 * System.out.println("현재 고객 정보 : "); System.out.println("이름 " + userName + " 연락처 "+ userMobile); // 메뉴 번호가 1일 때 입력된 고객 이름과 연락처 출력
					 */
					menuGuestInfo(userName, userMobile);
					break;
				case 2:
//				System.out.println("장바구니 상품 목록 보기 : ");
					menuCartItemList();
					break;
				case 3:
//				System.out.println("장바구니 비우기: ");
					menuCartClear();
					break;
				case 4:
//				System.out.println("장바구니에 항목 추가하기 : ");
					//menuCartAddItem(mbook);
					menuCartAddItem(mBookList);
					break;
				case 5:
//				System.out.println("5. 장바구니의 항목 수량 줄이기");
					menuCartRemoveItemCount();
					break;
				case 6:
//				System.out.println("6. 장바구니의 항목 삭제하기");
					menuCartRemoveItem();
					break;
				case 7:
//				System.out.println("7. 영수증 표시하기");
					menuCartBill();
					break;
				case 8:
//				System.out.println("8. 종료");
					menuExit();
					quit = true; // quit에 true를 넣어 반복문 종료 조건을 충족
					break;
				case 9:
					menuAdminLogin();
					break;
				}
			}
		}
	}
}

'한빛아카데미 - JAVA 마스터' 교재의 프로젝트 내용입니다.


프로젝트 구조도

 

PART 8 장바구니 항목 삭제 및 비우기

 

class Item - 추상 클래스 생성

 public abstract class Item { // 추상 클래스
	String bookId;
	String name;
	int unitPrice;
	
	public Item(String bookId, String name, int unitPrice) {
		this.bookId = bookId;
		this.name = name;
		this.unitPrice = unitPrice;
	}
	
	abstract String getBookId();
	
	abstract String getName();
	
	abstract int getUnitPrice();
	
	abstract void setBookId(String bookId);
	
	abstract void setName(String name);
	
	abstract void setUnitPrice(int unitPrice);
	
}

 

class Book - Item 추상 클래스의 자식 클래스 Book 생성

public class Book extends Item { // Item 추상 클래스의 자식 클래스 Book 생성
	private String author;
	private String description;
	private String category;
	private String releaseDate;
	
	public Book(String bookId, String name, int unitPrice) {
		super(bookId, name, unitPrice);
	}
	
	public Book(String bookId, String name, int unitPrice, String author, String description, String category, String releaseDate) {
		super(bookId, name, unitPrice);
		this.author = author;
		this.description = description;
		this.category = category;
		this.releaseDate = releaseDate;
	}
	
	public String getBookId() {
		return bookId;
	}
	
	public void setBookId(String bookId) {
		this.bookId = bookId;
	}
	
	public String getName() {
		return name;
	}
	
	public void setName(String name) {
		this.name = name;
	}
	
	public int getUnitPrice() {
		return unitPrice;
	}
	
	public void setUnitPrice(int unitPrice) {
		this.unitPrice = unitPrice;
	}
	

	public String getAuthor() {
		return author;
	}

	public void setAuthor(String author) {
		this.author = author;
	}

	public String getDescription() {
		return description;
	}

	public void setDescription(String description) {
		this.description = description;
	}

	public String getCategory() {
		return category;
	}

	public void setCategory(String category) {
		this.category = category;
	}

	public String getReleaseDate() {
		return releaseDate;
	}

	public void setReleaseDate(String releaseDate) {
		this.releaseDate = releaseDate;
	}
	
	
}

 

class CartItem -  Book 클래스를 적용하기 위해 파일 수정

public class CartItem {

	// private String[] itemBook = new String[7];
	private Book itemBook;
	private String bookID;
	private int quantity;
	private int totalPrice;

	public CartItem() {
		// TODO Auto-generated constructor stub
	}

	/*
	 * public CartItem(String[] book) { this.itemBook = book; this.bookID = book[0];
	 * this.quantity = 1; updateTotalPrice(); }
	 * 
	 * public String[] getItemBook() { return itemBook; }
	 * 
	 * public void setItemBook(String[] itemBook) { this.itemBook = itemBook; }
	 */
	public CartItem(Book booklist) {
		this.itemBook = booklist;
		this.bookID = booklist.getBookId();
		this.quantity = 1;
		updateTotalPrice();
	}

	public Book getItemBook() {
		return itemBook;
	}

	public void setItemBook(Book itemBook) {
		this.itemBook = itemBook;
	}

	public void setTotalPrice(int totalPrice) {
		this.totalPrice = totalPrice;
	}

	public String getBookID() {
		return bookID;
	}

	public void setBookID(String bookID) {
		this.bookID = bookID;
		this.updateTotalPrice();
	}

	public int getQuantity() {
		return quantity;
	}

	public void setQuantity(int quantity) {
		this.quantity = quantity;
		this.updateTotalPrice();
	}

	public int getTotalPrice() {
		return totalPrice;
	}

	public void updateTotalPrice() {
		// totalPrice = Integer.parseInt(this.itemBook[2]) * this.quantity;
		totalPrice = this.itemBook.getUnitPrice() * this.quantity;
	}
}

 

class CartInterface - 장바구니 처리의 메서드를 정의하기 위한 인터페이스 생성

public interface CartInterface { // 장바구니 처리의 메서드를 정의하기 위한 인터페이스 생성
	
	void printBookList(Book[] p); // 전체 도서 정보 목록 출력
	boolean isCartInBook(String id); /// 장바구니에 담긴 도서의 ID와 장바구니에 담을 도서의 ID를 비교하는 메서드
	void insertBook(Book p); // CartItem에 도서 정보를 등록하는 메서드
	void removeCart(int numId); // 장바구니 순번 numId의 항목을 삭제하는 메서드
	void deleteBook(); // 장바구니의 모든 항목을 삭제하는 메서드
	
}

 

class Cart - CartInterface 인터페이스의 자식 클래스 Cart 생성

public class Cart implements CartInterface { // CartInterface 인터페이스의 자식 클래스 Cart 생성
	
	static final int NUM_BOOK = 3;
	CartItem[] mCartItem = new CartItem[NUM_BOOK];
	static int mCartCount = 0;
	
	public Cart() {
		
	}
	
	public void printBookList(Book[] booklist) { // 전체 도서 정보 목록 출력 구현
		for(int i = 0; i< booklist.length; i++) {
			System.out.print(booklist[i].getBookId() + " | ");
			System.out.print(booklist[i].getName() + " | ");
			System.out.print(booklist[i].getUnitPrice() + " | ");
			System.out.print(booklist[i].getAuthor() + " | ");
			System.out.print(booklist[i].getDescription() + " | ");
			System.out.print(booklist[i].getCategory() + " | ");
			System.out.print(booklist[i].getReleaseDate() + " | ");
			System.out.println("");
		}
	}
	
	public void insertBook(Book book) { // CartItem에 도서 정보를 등록하는 메서드 구현
		mCartItem[mCartCount++] = new CartItem(book);
	}
	
	public void deleteBook() { // 장바구니의 모든 항목을 삭제하는 메서드 구현
		mCartItem = new CartItem[NUM_BOOK];
		mCartCount = 0;
	}
	
	public void printCart() {
		System.out.println("장바구니 상품 목록 :");
		System.out.println("-----------------------------------------------");
		System.out.println("       도서ID \t|     수 량 \t|       합 계");
		for(int i = 0; i < mCartCount; i++) {
			System.out.print("     "+mCartItem[i].getBookID() + "\t| ");
			System.out.print("     "+mCartItem[i].getQuantity() + "\t| ");
			System.out.print("     "+mCartItem[i].getTotalPrice());
			System.out.println("  ");
		}
		System.out.println("-----------------------------------------------");
	}
	
	public boolean isCartInBook(String bookId) { // 장바구니에 담긴 도서의 ID와 장바구니에 담을 도서의 ID를 비교하는 메서드 구현
		boolean flag = false;
		for(int i = 0; i < mCartCount; i++) {
			if(bookId == mCartItem[i].getBookID()) {
				mCartItem[i].setQuantity(mCartItem[i].getQuantity()+1);
				flag = true;
			}
		}
		return flag;
	}

	public void removeCart(int numId) { // 장바구니 순번 numId의 항목을 삭제하는 메서드 구현
		CartItem[] cartItem = new CartItem[NUM_BOOK];
		int num = 0;
		
		for (int i = 0; i < mCartCount; i++)
			if (numId != i)
				cartItem[num++] = mCartItem[i];
				
		
		mCartCount = num;
		mCartItem = cartItem;
	}

}

 

class Welcome - Book 클래스를 이용하여 도서 정보를 저장하기 위해 파일 수정

- BookList(), menuCartRemoveItem(), menuCartClear(), menuCartAddItem(), menuCartAddItem(), isCartInBook(), menuCartItemList() 메서드 수정

import java.util.Scanner;

public class Welcome {
	static final int NUM_BOOK = 3; // 도서의 개수에 대한 상수 NUM_BOOK 선언
	static final int NUM_ITEM = 7; // 도서 정보의 개수에 대한 상수 NUM_ITEM 선언
	// static CartItem[] mCartItem = new CartItem[NUM_BOOK];
	// static int mCartCount = 0;
	static Cart mCart = new Cart(); // Cart 클래스를 사용하기 위한 객체 생성
	static User mUser;

	public static void menuIntroduction() { // 메뉴 출력하는 메서드
		System.out.println("***************************************");
		System.out.println(" 1. 고객 정보 확인하기 \t4. 바구니에 항목 추가하기");
		System.out.println(" 2. 장바구니 상품 목록 보기 \t5. 장바구니의 항목 수량 줄이기");
		System.out.println(" 3. 장바구니 비우기 \t6. 장바구니의 항목 삭제하기");
		System.out.println(" 7. 영수증 표시하기 \t8. 종료");
		System.out.println(" 9. 관리자 로그인");
		System.out.println("***************************************");
	}

	public static void menuGuestInfo(String name, int mobile) { // 사용자 정보 출력하는 메서드
		System.out.println("현재 고객 정보 : ");
		System.out.println("이름 "+ mUser.getName() + " 연락처 " + mUser.getPhone());
		
		// System.out.println("이름 " + name + " 연락처 " + mobile);
		// Person person = new Person(name, mobile);
		// System.out.println("이름 " + person.getName() + "   연락처 " + person.getPhone());
	}

	public static void menuCartItemList() {
		/*
		System.out.println("장바구니 상품 목록 :");
		System.out.println("-----------------------------------------------");
		System.out.println("       도서ID \t|     수 량 \t|       합 계");
		for(int i = 0; i < mCartCount; i++) {
			System.out.print("     "+mCartItem[i].getBookID() + "\t| ");
			System.out.print("     "+mCartItem[i].getQuantity() + "\t| ");
			System.out.println("     "+mCartItem[i].getTotalPrice());
		}
		System.out.println("-----------------------------------------------");
		*/
		
		if(mCart.mCartCount >= 0) {
			mCart.printCart();
		}
	}

	public static void menuCartClear() { // 장바구니 모든 항목 삭제하는 메서드
		//System.out.println("장바구니 비우기: ");
		if(mCart.mCartCount == 0) {
			System.out.println("장바구니에 항목이 없습니다");
		}
		else {
			System.out.println("장바구니의 모든 항목을 삭제하겠습니까? Y | N ");
			Scanner input = new Scanner(System.in);
			String str = input.nextLine();
			
			if(str.toUpperCase().equals("Y")) {
				mCart.deleteBook();
			}
			
		}
	}

	public static void menuCartAddItem(Book[] booklist) { // String[][] book -> Book[] booklist 변경 매개변수 추가, 장바구니에 도서를 추가하는 메서드
		// System.out.println("장바구니에 항목 추가하기 : ");

		//BookList(book); // 도서 정보를 저장하는 메서드 호출
		BookList(booklist);
		/*
		for (int i = 0; i < NUM_BOOK; i++) { // 도서 정보 출력
			for (int j = 0; j < NUM_ITEM; j++)
				System.out.print(book[i][j] + " | ");
			System.out.println("");
		}
		*/
		mCart.printBookList(booklist);
		
		boolean quit = false;
		
		while(!quit) { // 장바구니에 항목을 추가하지 않을 때까지 반복하는 while문
			System.out.print("장바구니에 추가할 도서의 ID를 입력하세요 : ");
			
			Scanner input = new Scanner(System.in);
			String str = input.nextLine(); // 도서의 ID를 입력받음
			
			boolean flag = false;
			int numId = -1;
			
			for(int i = 0; i < NUM_BOOK; i++) { // 입력된 도서의 ID와 저장되어 있는 도서 정보의 ID가 일치하는지 확인하여
				if(str.equals(booklist[i].getBookId())) { // 일치하면 도서 정보의 numId(인덱스 번호)와 flag(일치 여부) 변수에 값을 변경하여 저장하고 반복문 종료
					numId = i;
					flag = true;
					break;
				}
			}
			
			if(flag) { // 변수 flag가 참이면(입력된 도서의 ID와 저장되어 있는 도서 정보의 ID가 일치하면) 반복문을 종료하고, 거짓이면 '다시 입력해 주세요' 출력
				System.out.println("장바구니에 추가하겠습니까? Y | N");
				str = input.nextLine(); // 장바구니에 도서 추가 여부를 위한 입력값을 받음
				
				if(str.toUpperCase().equals("Y")) { // 입력값을 대문자로 변경하여 Y이면 '도서가 장바구니에 추가되었습니다.' 출력
					System.out.println(booklist[numId].getBookId() + "도서가 장바구니에 추가되었습니다.");
					
					// 장바구니에 넣기
					if(!isCartInBook(booklist[numId].getBookId()))
							mCart.insertBook(booklist[numId]);
				}
				
				quit = true;
				
			} else
				System.out.println("다시 입력해 주세요");
		}
	}

	public static boolean isCartInBook(String bookId) { // 장바구니에 담긴 도서의 ID와 장바구니에 담을 도서의 ID를 비교하는 메서드
		/*
		boolean flag = false;
		for(int i = 0; i < mCartCount; i++) {
			if(bookId == mCartItem[i].getBookID()) {
				mCartItem[i].setQuantity(mCartItem[i].getQuantity()+1);
				flag = true;
			}
		}
		return flag;
		*/
		return mCart.isCartInBook(bookId);
	}

	public static void menuCartRemoveItemCount() {
		System.out.println("5. 장바구니의 항목 수량 줄이기");
	}

	public static void menuCartRemoveItem() { // 장바구니의 항목 삭제하는 메서드
		// System.out.println("6. 장바구니의 항목 삭제하기");
		if(mCart.mCartCount == 0)
			System.out.println("장바구니에 항목이 없습니다");
		else {
			menuCartItemList();
			boolean quit = false;
			while(!quit) {
				System.out.print("장바구니에서 삭제할 도서의 ID를 입력하세요 :");
				Scanner input = new Scanner(System.in);
				String str = input.nextLine();
				boolean flag = false;
				int numId = -1;
				
				for(int i = 0; i < mCart.mCartCount; i++) {
					if(str.equals(mCart.mCartItem[i].getBookID())) {
						numId = i;
						flag = true;
						break;
					}
				}
				
				if(flag) {
					System.out.println("장바구니의 항목을 삭제하시겠습니까? Y | N ");
					str = input.nextLine();
					if (str.toUpperCase().equals("Y")) {
						System.out.println(mCart.mCartItem[numId].getBookID() + "도서가 삭제되었습니다.");
						mCart.removeCart(numId); // Cart 클래스의 구현된 removeCart 메서드로 도서 삭제 진행
					}
					quit = true;
				}
				else System.out.println("다시 입력해 주세요");
			}
		}
	}

	public static void menuCartBill() {
		System.out.println("7. 영수증 표시하기");
	}

	public static void menuExit() {
		System.out.println("8. 종료");
	}
	
	public static void menuAdminLogin() {
		System.out.println("관리자 정보를 입력하세요");
		
		Scanner input = new Scanner(System.in);
		System.out.print("아이디: ");
		String adminId = input.next();
		
		System.out.print("비밀번호: ");
		String adminPW = input.next();
		
		Admin admin = new Admin(mUser.getName(), mUser.getPhone());
		if(adminId.equals(admin.getId()) && adminPW.equals(admin.getPassword())) {
			System.out.println("이름 "+admin.getName() + " 연락처 " + admin.getPhone());
			System.out.println("아이디 "+admin.getId() + " 비밀번호 "+admin.getPassword());
		}else
			System.out.println("관리자 정보가 일치하지 않습니다.");
	}

	public static void BookList(Book[] booklist) { // 도서 정보를 저장하는 메서드
		
		booklist[0] = new Book("ISBN1234", "쉽게 배우는 JSP 웹 프로그래밍", 27000);
		booklist[0].setAuthor("송미영");
		booklist[0].setDescription("단계별로 쇼핑몰을 구현하며 배우는 JSP 웹 프로그래밍");
		booklist[0].setCategory("IT전문서");
		booklist[0].setReleaseDate("2018/10/08");
		
		booklist[1] = new Book("ISBN1235", "안드로이드 프로그래밍", 33000);
		booklist[1].setAuthor("우재남");
		booklist[1].setDescription("실습 단계별 명쾌한 멘토링!");
		booklist[1].setCategory("IT전문서");
		booklist[1].setReleaseDate("2022/01/22");
		
		booklist[2] = new Book("ISBN1236", "스크래치", 22000);
		booklist[2].setAuthor("고광일");
		booklist[2].setDescription("컴퓨팅 사고력을 키우는 블록 코딩");
		booklist[2].setCategory("컴퓨터입문");
		booklist[2].setReleaseDate("2019/06/10");
		
		/*
		book[0][0] = "ISBN1234";
		book[0][1] = "쉽게 배우는 JSP 웹 프로그래밍";
		book[0][2] = "27000"; // 27,000
		book[0][3] = "송미영";
		book[0][4] = "단계별로 쇼핑몰을 구현하며 배우는 JSP 웹 프로그래밍 ";
		book[0][5] = "IT전문서";
		book[0][6] = "2018/10/08";

		book[1][0] = "ISBN1235";
		book[1][1] = "안드로이드 프로그래밍";
		book[1][2] = "33000"; // 33,000
		book[1][3] = "우재남";
		book[1][4] = "실습 단계별 명쾌한 멘토링!";
		book[1][5] = "IT전문서";
		book[1][6] = "2022/01/22";

		book[2][0] = "ISBN1236";
		book[2][1] = "스크래치";
		book[2][2] = "22000"; // 22,000
		book[2][3] = "고광일";
		book[2][4] = "컴퓨팅 사고력을 키우는 블록 코딩";
		book[2][5] = "컴퓨터입문";
		book[2][6] = "2019/06/10";
		*/
	}

	public static void main(String[] args) {
		// String[][] mbook = new String[NUM_BOOK][NUM_ITEM]; // 도서 정보를 저장할 mBook을 2차원 배열로 생성
		Book[] mBookList = new Book[NUM_BOOK];
		Scanner input = new Scanner(System.in);

		System.out.print("당신의 이름을 입력하세요 : ");
		String userName = input.next();

		System.out.print("연락처를 입력하세요 : ");
		int userMobile = input.nextInt();
		
		mUser = new User(userName, userMobile);

		String greeting = "Welcome to Shopping Mall";
		String tagline = "Welcome to Book Market!";

		boolean quit = false; // 종료 여부 설정 변수

		while (!quit) { // quit 변수가 true일 때까지 계속 반복			
			System.out.println("***************************************");
			System.out.println("\t" + greeting);
			System.out.println("\t" + tagline);

			/*
			 * 기존 메뉴 설명 주석 처리 System.out.println("***************************************");
			 * System.out.println("1. 고객 정보 확인하기 \t4. 바구니에 항목 추가하기");
			 * System.out.println("2. 장바구니 상품 목록 보기 \t5. 장바구니의 항목 수량 줄이기");
			 * System.out.println("3. 장바구니 비우기 \t6. 장바구니의 항목 삭제하기");
			 * System.out.println("7. 영수증 표시하기 \t8. 종료");
			 * System.out.println("***************************************");
			 */

			menuIntroduction(); // 메뉴 목록 출력 메서드 호출

			System.out.println("메뉴 번호를 선택해주세요 ");
			int n = input.nextInt();

//		System.out.println(n +"n번을 선택했습니다. ");

			if (n < 1 || n > 9) { // 메뉴 선택 번호가 1~9이 아니면 아래 문자열 출력
				System.out.println("1부터 8까지의 숫자를 입력하세요.");
			}

			else {
				switch (n) { // switch문을 이용하여 메뉴 선택 번호별 정보 출력
				case 1:
					/*
					 * 기존 내용 주석 처리 
					 * System.out.println("현재 고객 정보 : "); System.out.println("이름 " + userName + " 연락처 "+ userMobile); // 메뉴 번호가 1일 때 입력된 고객 이름과 연락처 출력
					 */
					menuGuestInfo(userName, userMobile);
					break;
				case 2:
//				System.out.println("장바구니 상품 목록 보기 : ");
					menuCartItemList();
					break;
				case 3:
//				System.out.println("장바구니 비우기: ");
					menuCartClear();
					break;
				case 4:
//				System.out.println("장바구니에 항목 추가하기 : ");
					//menuCartAddItem(mbook);
					menuCartAddItem(mBookList);
					break;
				case 5:
//				System.out.println("5. 장바구니의 항목 수량 줄이기");
					menuCartRemoveItemCount();
					break;
				case 6:
//				System.out.println("6. 장바구니의 항목 삭제하기");
					menuCartRemoveItem();
					break;
				case 7:
//				System.out.println("7. 영수증 표시하기");
					menuCartBill();
					break;
				case 8:
//				System.out.println("8. 종료");
					menuExit();
					quit = true; // quit에 true를 넣어 반복문 종료 조건을 충족
					break;
				case 9:
					menuAdminLogin();
					break;
				}
			}
		}
	}
}

'한빛아카데미 - JAVA 마스터' 교재의 프로젝트 내용입니다.


프로젝트 구조도

 

PART 7 사용자, 관리자 정보 관리 및 관리자 로그인 기능 만들기

 

class Welcome - 내용 수정 및 추가

- main(), menuGuestInfo(), menuIntroduction() 변경

- menuAdminLogin() 추가

import java.util.Scanner;

public class Welcome {
	static final int NUM_BOOK = 3; // 도서의 개수에 대한 상수 NUM_BOOK 선언
	static final int NUM_ITEM = 7; // 도서 정보의 개수에 대한 상수 NUM_ITEM 선언
	static CartItem[] mCartItem = new CartItem[NUM_BOOK];
	static int mCartCount = 0;
	static User mUser;

	public static void menuIntroduction() { // 메뉴 출력하는 메서드
		System.out.println("***************************************");
		System.out.println(" 1. 고객 정보 확인하기 \t4. 바구니에 항목 추가하기");
		System.out.println(" 2. 장바구니 상품 목록 보기 \t5. 장바구니의 항목 수량 줄이기");
		System.out.println(" 3. 장바구니 비우기 \t6. 장바구니의 항목 삭제하기");
		System.out.println(" 7. 영수증 표시하기 \t8. 종료");
		System.out.println(" 9. 관리자 로그인");
		System.out.println("***************************************");
	}

	public static void menuGuestInfo(String name, int mobile) { // 고객 정보 확인하는 메서드
		System.out.println("현재 고객 정보 : ");
		System.out.println("이름 "+ mUser.getName() + " 연락처 " + mUser.getPhone());
		// System.out.println("이름 " + name + " 연락처 " + mobile);
		// Person person = new Person(name, mobile);
		// System.out.println("이름 " + person.getName() + "   연락처 " + person.getPhone());
	}

	public static void menuCartItemList() {  // 장바구니 상품 목록 확인하는 메서드
		System.out.println("장바구니 상품 목록 :");
		System.out.println("-----------------------------------------------");
		System.out.println("       도서ID \t|     수 량 \t|       합 계");
		for(int i = 0; i < mCartCount; i++) {
			System.out.print("     "+mCartItem[i].getBookID() + "\t| ");
			System.out.print("     "+mCartItem[i].getQuantity() + "\t| ");
			System.out.println("     "+mCartItem[i].getTotalPrice());
		}
		System.out.println("-----------------------------------------------");
	}

	public static void menuCartClear() {  // 장바구니 모든 항목 삭제하는 메서드
		System.out.println("장바구니 비우기: ");
	}

	public static void menuCartAddItem(String[][] book) { // String[][] book 매개변수 추가, 장바구니에 도서를 추가하는 메서드
		// System.out.println("장바구니에 항목 추가하기 : ");

		BookList(book); // 도서 정보를 저장하는 메서드 호출
		
		for (int i = 0; i < NUM_BOOK; i++) { // 도서 정보 출력
			for (int j = 0; j < NUM_ITEM; j++)
				System.out.print(book[i][j] + " | ");
			System.out.println("");
		}
		
		boolean quit = false;
		
		while(!quit) { // 장바구니에 항목을 추가하지 않을 때까지 반복하는 while문
			System.out.print("장바구니에 추가할 도서의 ID를 입력하세요 : ");
			
			Scanner input = new Scanner(System.in);
			String str = input.nextLine(); // 도서의 ID를 입력받음
			
			boolean flag = false;
			int numId = -1;
			
			for(int i = 0; i < NUM_BOOK; i++) { // 입력된 도서의 ID와 저장되어 있는 도서 정보의 ID가 일치하는지 확인하여
				if(str.equals(book[i][0])) { // 일치하면 도서 정보의 numId(인덱스 번호)와 flag(일치 여부) 변수에 값을 변경하여 저장하고 반복문 종료
					numId = i;
					flag = true;
					break;
				}
			}
			
			if(flag) { // 변수 flag가 참이면(입력된 도서의 ID와 저장되어 있는 도서 정보의 ID가 일치하면) 반복문을 종료하고, 거짓이면 '다시 입력해 주세요' 출력
				System.out.println("장바구니에 추가하겠습니까? Y | N");
				str = input.nextLine(); // 장바구니에 도서 추가 여부를 위한 입력값을 받음
				
				if(str.toUpperCase().equals("Y")) { // 입력값을 대문자로 변경하여 Y이면 '도서가 장바구니에 추가되었습니다.' 출력
					System.out.println(book[numId][0] + "도서가 장바구니에 추가되었습니다.");
					
					// 장바구니에 넣기
					if(!isCartInBook(book[numId][0]))
						mCartItem[mCartCount++] = new CartItem(book[numId]);
				}
				
				quit = true;
				
			} else
				System.out.println("다시 입력해 주세요");
		}
	}

	public static boolean isCartInBook(String bookId) { // 장바구니에 담긴 도서의 ID와 장바구니에 담을 도서의 ID를 비교하는 메서드
		boolean flag = false;
		for(int i = 0; i < mCartCount; i++) {
			if(bookId == mCartItem[i].getBookID()) {
				mCartItem[i].setQuantity(mCartItem[i].getQuantity()+1);
				flag = true;
			}
		}
		return flag;
	}

	public static void menuCartRemoveItemCount() {  // 장바구니의 항목 수량 줄이는 메서드
		System.out.println("5. 장바구니의 항목 수량 줄이기");
	}

	public static void menuCartRemoveItem() {  // 장바구니의 항목 삭제하는 메서드
		System.out.println("6. 장바구니의 항목 삭제하기");
	}

	public static void menuCartBill() {  // 영수증 표시하는 메서드
		System.out.println("7. 영수증 표시하기");
	}

	public static void menuExit() {  // 종료하는 메서드
		System.out.println("8. 종료");
	}
	
	public static void menuAdminLogin() { // 관리자 로그인 메서드
		System.out.println("관리자 정보를 입력하세요");
		
		Scanner input = new Scanner(System.in);
		System.out.print("아이디: ");
		String adminId = input.next();
		
		System.out.print("비밀번호: ");
		String adminPW = input.next();
		
		Admin admin = new Admin(mUser.getName(), mUser.getPhone());
		if(adminId.equals(admin.getId()) && adminPW.equals(admin.getPassword())) {
			System.out.println("이름 "+admin.getName() + " 연락처 " + admin.getPhone());
			System.out.println("아이디 "+admin.getId() + " 비밀번호 "+admin.getPassword());
		}else
			System.out.println("관리자 정보가 일치하지 않습니다.");
	}

	public static void BookList(String[][] book) { // 도서 정보를 저장하는 메서드

		book[0][0] = "ISBN1234";
		book[0][1] = "쉽게 배우는 JSP 웹 프로그래밍";
		book[0][2] = "27000"; // 27,000
		book[0][3] = "송미영";
		book[0][4] = "단계별로 쇼핑몰을 구현하며 배우는 JSP 웹 프로그래밍 ";
		book[0][5] = "IT전문서";
		book[0][6] = "2018/10/08";

		book[1][0] = "ISBN1235";
		book[1][1] = "안드로이드 프로그래밍";
		book[1][2] = "33000"; // 33,000
		book[1][3] = "우재남";
		book[1][4] = "실습 단계별 명쾌한 멘토링!";
		book[1][5] = "IT전문서";
		book[1][6] = "2022/01/22";

		book[2][0] = "ISBN1236";
		book[2][1] = "스크래치";
		book[2][2] = "22000"; // 22,000
		book[2][3] = "고광일";
		book[2][4] = "컴퓨팅 사고력을 키우는 블록 코딩";
		book[2][5] = "컴퓨터입문";
		book[2][6] = "2019/06/10";
	}

	public static void main(String[] args) {
		String[][] mbook = new String[NUM_BOOK][NUM_ITEM]; // 도서 정보를 저장할 mBook을 2차원 배열로 생성
		// PART2에서 작성한 내용
		Scanner input = new Scanner(System.in);

		System.out.print("당신의 이름을 입력하세요 : ");
		String userName = input.next();

		System.out.print("연락처를 입력하세요 : ");
		int userMobile = input.nextInt();
		
		mUser = new User(userName, userMobile);

		String greeting = "Welcome to Shopping Mall";
		String tagline = "Welcome to Book Market!";

		boolean quit = false; // 종료 여부 설정 변수

		while (!quit) { // quit 변수가 true일 때까지 계속 반복			
			System.out.println("***************************************");
			System.out.println("\t" + greeting);
			System.out.println("\t" + tagline);

			/*
			 * 기존 메뉴 설명 주석 처리 System.out.println("***************************************");
			 * System.out.println("1. 고객 정보 확인하기 \t4. 바구니에 항목 추가하기");
			 * System.out.println("2. 장바구니 상품 목록 보기 \t5. 장바구니의 항목 수량 줄이기");
			 * System.out.println("3. 장바구니 비우기 \t6. 장바구니의 항목 삭제하기");
			 * System.out.println("7. 영수증 표시하기 \t8. 종료");
			 * System.out.println("***************************************");
			 */

			menuIntroduction(); // 메뉴 목록 출력 메서드 호출

			System.out.println("메뉴 번호를 선택해주세요 ");
			int n = input.nextInt();

//		System.out.println(n +"n번을 선택했습니다. ");

			if (n < 1 || n > 9) { // 메뉴 선택 번호가 1~9이 아니면 아래 문자열 출력
				System.out.println("1부터 8까지의 숫자를 입력하세요.");
			}

			else {
				switch (n) { // switch문을 이용하여 메뉴 선택 번호별 정보 출력
				case 1:
					/*
					 * 기존 내용 주석 처리 
					 * System.out.println("현재 고객 정보 : "); System.out.println("이름 " + userName + " 연락처 "+ userMobile); // 메뉴 번호가 1일 때 입력된 고객 이름과 연락처 출력
					 */
					menuGuestInfo(userName, userMobile);
					break;
				case 2:
//				System.out.println("장바구니 상품 목록 보기 : ");
					menuCartItemList();
					break;
				case 3:
//				System.out.println("장바구니 비우기: ");
					menuCartClear();
					break;
				case 4:
//				System.out.println("장바구니에 항목 추가하기 : ");
					menuCartAddItem(mbook);
					break;
				case 5:
//				System.out.println("5. 장바구니의 항목 수량 줄이기");
					menuCartRemoveItemCount();
					break;
				case 6:
//				System.out.println("6. 장바구니의 항목 삭제하기");
					menuCartRemoveItem();
					break;
				case 7:
//				System.out.println("7. 영수증 표시하기");
					menuCartBill();
					break;
				case 8:
//				System.out.println("8. 종료");
					menuExit();
					quit = true; // quit에 true를 넣어 반복문 종료 조건을 충족
					break;
				case 9:
					menuAdminLogin();
					break;
				}
			}
		}
	}
}

 

class User 추가 - Person 클래스로부터 상속받는 자식 클래스

public class User extends Person {
	
	public User(String name, int phone) {
		super(name, phone);
	}
	
	public User(String username, int phone, String address) {
		super(username, phone, address);
	}
}

 

class Admin 추가 - Person 클래스로부터 상속받는 자식 클래스

public class Admin extends Person {
	private String id = "Admin";
	private String password = "Admin1234";
	
	public Admin(String name, int phone) {
		super(name, phone);
	}

	public String getId() {
		return id;
	}

	public String getPassword() {
		return password;
	}
}

 

'한빛아카데미 - JAVA 마스터' 교재의 프로젝트 내용입니다.


프로젝트 구조도

 

PART6 장바구니에 항목 추가하기

 

class Welcome - 내용 수정 및 추가

- menuGuestInfo(), menuCartAddItem(), menuCartItemList() 변경

- isCartInBook() 추가

import java.util.Scanner;

public class Welcome {
	static final int NUM_BOOK = 3; // 도서의 개수에 대한 상수 NUM_BOOK 선언
	static final int NUM_ITEM = 7; // 도서 정보의 개수에 대한 상수 NUM_ITEM 선언
	static CartItem[] mCartItem = new CartItem[NUM_BOOK];
	static int mCartCount = 0;

	public static void menuIntroduction() { // 메뉴 출력하는 메서드
		System.out.println("***************************************");
		System.out.println("1. 고객 정보 확인하기 \t4. 바구니에 항목 추가하기");
		System.out.println("2. 장바구니 상품 목록 보기 \t5. 장바구니의 항목 수량 줄이기");
		System.out.println("3. 장바구니 비우기 \t6. 장바구니의 항목 삭제하기");
		System.out.println("7. 영수증 표시하기 \t8. 종료");
		System.out.println("***************************************");
	}

	public static void menuGuestInfo(String name, int mobile) { // 고객 정보 확인하는 메서드
		System.out.println("현재 고객 정보 : ");
		// System.out.println("이름 " + Name + " 연락처 " + Mobile);
		
		Person person = new Person(name, mobile);
		System.out.println("이름 : " + person.getName() + " 연락처 " + person.getPhone()); 
	}

	public static void menuCartItemList() { // 장바구니 상품 목록 확인하는 메서드
		System.out.println("장바구니 상품 목록 :");
		System.out.println("-----------------------------------------------");
		System.out.println("       도서ID \t|     수 량 \t|       합 계");
		for(int i = 0; i < mCartCount; i++) {
			System.out.print("     "+mCartItem[i].getBookID() + "\t| ");
			System.out.print("     "+mCartItem[i].getQuantity() + "\t| ");
			System.out.println("     "+mCartItem[i].getTotalPrice());
		}
		System.out.println("-----------------------------------------------");
	}

	public static void menuCartClear() { // 장바구니 모든 항목 삭제하는 메서드
		System.out.println("장바구니 비우기: ");
	}

	public static void menuCartAddItem(String[][] book) { // String[][] book 매개변수 추가, 장바구니에 도서를 추가하는 메서드
		// System.out.println("장바구니에 항목 추가하기 : ");

		BookList(book); // 도서 정보를 저장하는 메서드 호출
		for (int i = 0; i < NUM_BOOK; i++) { // 도서 정보 출력
			for (int j = 0; j < NUM_ITEM; j++)
				System.out.print(book[i][j] + " | ");
			System.out.println("");
		}
		
		boolean quit = false;
		
		while(!quit) { // 장바구니에 항목을 추가하지 않을 때까지 반복하는 while문
			System.out.print("장바구니에 추가할 도서의 ID를 입력하세요 : ");
			
			Scanner input = new Scanner(System.in);
			String str = input.nextLine(); // 도서의 ID를 입력받음
			
			boolean flag = false;
			int numId = -1;
			
			for(int i = 0; i < NUM_BOOK; i++) { // 입력된 도서의 ID와 저장되어 있는 도서 정보의 ID가 일치하는지 확인하여
				if(str.equals(book[i][0])) { // 일치하면 도서 정보의 numId(인덱스 번호)와 flag(일치 여부) 변수에 값을 변경하여 저장하고 반복문 종료
					numId = i;
					flag = true;
					break;
				}
			}
			
			if(flag) { // 변수 flag가 참이면(입력된 도서의 ID와 저장되어 있는 도서 정보의 ID가 일치하면) 반복문을 종료하고, 거짓이면 '다시 입력해 주세요' 출력
				System.out.println("장바구니에 추가하겠습니까? Y | N");
				str = input.nextLine(); // 장바구니에 도서 추가 여부를 위한 입력값을 받음
				
				if(str.toUpperCase().equals("Y")) { // 입력값을 대문자로 변경하여 Y이면 '도서가 장바구니에 추가되었습니다.' 출력
					System.out.println(book[numId][0] + "도서가 장바구니에 추가되었습니다.");
					
					// 장바구니에 넣기
					if(!isCartInBook(book[numId][0]))
						mCartItem[mCartCount++] = new CartItem(book[numId]);
				}
				
				quit = true;
				
			} else
				System.out.println("다시 입력해 주세요");
		}
	}

	public static boolean isCartInBook(String bookId) { // 장바구니에 담긴 도서의 ID와 장바구니에 담을 도서의 ID를 비교하는 메서드
		boolean flag = false;
		for(int i = 0; i < mCartCount; i++) {
			if(bookId == mCartItem[i].getBookID()) {
				mCartItem[i].setQuantity(mCartItem[i].getQuantity()+1);
				flag = true;
			}
		}
		return flag;
	}

	public static void menuCartRemoveItemCount() { // 장바구니의 항목 수량 줄이는 메서드
		System.out.println("5. 장바구니의 항목 수량 줄이기");
	}

	public static void menuCartRemoveItem() { // 장바구니의 항목 삭제하는 메서드
		System.out.println("6. 장바구니의 항목 삭제하기");
	}

	public static void menuCartBill() { // 영수증 표시하는 메서드
		System.out.println("7. 영수증 표시하기");
	}

	public static void menuExit() { // 종료하는 메서드
		System.out.println("8. 종료");
	}

	public static void BookList(String[][] book) { // 도서 정보를 저장하는 메서드

		book[0][0] = "ISBN1234";
		book[0][1] = "쉽게 배우는 JSP 웹 프로그래밍";
		book[0][2] = "27000"; // 27,000
		book[0][3] = "송미영";
		book[0][4] = "단계별로 쇼핑몰을 구현하며 배우는 JSP 웹 프로그래밍 ";
		book[0][5] = "IT전문서";
		book[0][6] = "2018/10/08";

		book[1][0] = "ISBN1235";
		book[1][1] = "안드로이드 프로그래밍";
		book[1][2] = "33000"; // 33,000
		book[1][3] = "우재남";
		book[1][4] = "실습 단계별 명쾌한 멘토링!";
		book[1][5] = "IT전문서";
		book[1][6] = "2022/01/22";

		book[2][0] = "ISBN1236";
		book[2][1] = "스크래치";
		book[2][2] = "22000"; // 22,000
		book[2][3] = "고광일";
		book[2][4] = "컴퓨팅 사고력을 키우는 블록 코딩";
		book[2][5] = "컴퓨터입문";
		book[2][6] = "2019/06/10";
	}

	public static void main(String[] args) {
		String[][] mbook = new String[NUM_BOOK][NUM_ITEM]; // 도서 정보를 저장할 mBook을 2차원 배열로 생성
		// PART2에서 작성한 내용
		Scanner input = new Scanner(System.in);

		System.out.print("당신의 이름을 입력하세요 : ");
		String userName = input.next();

		System.out.print("연락처를 입력하세요 : ");
		int userMobile = input.nextInt();

		String greeting = "Welcome to Shopping Mall";
		String tagline = "Welcome to Book Market!";

		boolean quit = false; // 종료 여부 설정 변수

		while (!quit) { // quit 변수가 true일 때까지 계속 반복			
			System.out.println("***************************************");
			System.out.println("\t" + greeting);
			System.out.println("\t" + tagline);

			/*
			 * 기존 메뉴 설명 주석 처리 System.out.println("***************************************");
			 * System.out.println("1. 고객 정보 확인하기 \t4. 바구니에 항목 추가하기");
			 * System.out.println("2. 장바구니 상품 목록 보기 \t5. 장바구니의 항목 수량 줄이기");
			 * System.out.println("3. 장바구니 비우기 \t6. 장바구니의 항목 삭제하기");
			 * System.out.println("7. 영수증 표시하기 \t8. 종료");
			 * System.out.println("***************************************");
			 */

			menuIntroduction(); // 메뉴 목록 출력 메서드 호출

			System.out.println("메뉴 번호를 선택해주세요 ");
			int n = input.nextInt();

//		System.out.println(n +"n번을 선택했습니다. ");

			if (n < 1 || n > 8) { // 메뉴 선택 번호가 1~8이 아니면 아래 문자열 출력
				System.out.println("1부터 8까지의 숫자를 입력하세요.");
			}

			else {
				switch (n) { // switch문을 이용하여 메뉴 선택 번호별 정보 출력
				case 1:
					/*
					 * 기존 내용 주석 처리 
					 * System.out.println("현재 고객 정보 : "); System.out.println("이름 " + userName + " 연락처 "+ userMobile); // 메뉴 번호가 1일 때 입력된 고객 이름과 연락처 출력
					 */
					menuGuestInfo(userName, userMobile);
					break;
				case 2:
//				System.out.println("장바구니 상품 목록 보기 : ");
					menuCartItemList();
					break;
				case 3:
//				System.out.println("장바구니 비우기: ");
					menuCartClear();
					break;
				case 4:
//				System.out.println("장바구니에 항목 추가하기 : ");
					menuCartAddItem(mbook);
					break;
				case 5:
//				System.out.println("5. 장바구니의 항목 수량 줄이기");
					menuCartRemoveItemCount();
					break;
				case 6:
//				System.out.println("6. 장바구니의 항목 삭제하기");
					menuCartRemoveItem();
					break;
				case 7:
//				System.out.println("7. 영수증 표시하기");
					menuCartBill();
					break;
				case 8:
//				System.out.println("8. 종료");
					menuExit();
					quit = true; // quit에 true를 넣어 반복문 종료 조건을 충족
					break;

				}
			}
		}
	}
}

 

class CartItem - 클래스 생성

public class CartItem {
	
	private String[] itemBook = new String[7];
	private String bookID;
	private int quantity;
	private int  totalPrice;
	
	public CartItem() {
		// TODO Auto-generated constructor stub
	}
	
	public CartItem(String[] book) {
		this.itemBook = book;
		this.bookID = book[0];
		this.quantity = 1;	
		updateTotalPrice();
	}
	
	public String[] getItemBook() {
		return itemBook;
	}

	public void setItemBook(String[] itemBook) {
		this.itemBook = itemBook;
	}
	public String getBookID() {
		return bookID;
	}

	public void setBookID(String bookID) {
		this.bookID = bookID;
		this.updateTotalPrice();
	}

	public int getQuantity() {
		return quantity;
	}
	
	public void setQuantity(int quantity) {
		this.quantity = quantity;
		this.updateTotalPrice();
	}
	
	public int getTotalPrice() {
		return totalPrice;
	}

	public void updateTotalPrice() {
		totalPrice = Integer.parseInt(this.itemBook[2]) * this.quantity; // Integer.parseInt: 문자열을 숫자로 변경하는 메서드
	}

}

 

class Person - 클래스 생성

public class Person {
    private String name;
    private int phone;
    private String address;  

    public Person(String name, int phone) {
        this.name = name;
        this.phone = phone;
             
    }
    
    public Person(String name, int phone, String address) {
        this.name = name;
        this.phone = phone;
        this.address = address;      
    }
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getPhone() {
        return phone;
    }
    
    public void setPhone(int phone) {
        this.phone = phone;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }
}

 

'한빛아카데미 - JAVA 마스터' 교재의 프로젝트 내용입니다.


프로젝트 구조도

 

PART5 도서 목록 표시하기

 

class Welcome 내용 수정 및 추가

- main(), menuCartAddItem() 수정

- BookList() 추가

import java.util.Scanner;

public class Welcome {
	static final int NUM_BOOK = 3; // 도서의 개수에 대한 상수 NUM_BOOK 선언
	static final int NUM_ITEM = 7; // 도서 정보의 개수에 대한 상수 NUM_ITEM 선언

	public static void menuIntroduction() { // 메뉴 출력하는 메서드
		System.out.println("***************************************");
		System.out.println("1. 고객 정보 확인하기 \t4. 바구니에 항목 추가하기");
		System.out.println("2. 장바구니 상품 목록 보기 \t5. 장바구니의 항목 수량 줄이기");
		System.out.println("3. 장바구니 비우기 \t6. 장바구니의 항목 삭제하기");
		System.out.println("7. 영수증 표시하기 \t8. 종료");
		System.out.println("***************************************");
	}

	public static void menuGuestInfo(String Name, int Mobile) { // 고객 정보 확인하는 메서드
		System.out.println("현재 고객 정보 : ");
		System.out.println("이름 " + Name + " 연락처 " + Mobile);
	}

	public static void menuCartItemList() {
		System.out.println("장바구니 상품 목록 보기 : ");
	}

	public static void menuCartClear() { // 장바구니 모든 항목 삭제하는 메서드
		System.out.println("장바구니 비우기: ");
	}

	public static void menuCartAddItem(String[][] book) { // String[][] book 매개변수 추가, 장바구니에 도서를 추가하는 메서드
		// System.out.println("장바구니에 항목 추가하기 : ");

		BookList(book); // 도서 정보를 저장하는 메서드 호출
		for (int i = 0; i < NUM_BOOK; i++) { // 도서 정보 출력
			for (int j = 0; j < NUM_ITEM; j++)
				System.out.print(book[i][j] + " | ");
			System.out.println("");
		}
		
		boolean quit = false;
		
		while(!quit) { // 장바구니에 항목을 추가하지 않을 때까지 반복하는 while문
			System.out.print("장바구니에 추가할 도서의 ID를 입력하세요 : ");
			
			Scanner input = new Scanner(System.in);
			String str = input.nextLine(); // 도서의 ID를 입력받음
			
			boolean flag = false;
			int numId = -1;
			
			for(int i = 0; i < NUM_BOOK; i++) { // 입력된 도서의 ID와 저장되어 있는 도서 정보의 ID가 일치하는지 확인하여
				if(str.equals(book[i][0])) { // 일치하면 도서 정보의 numId(인덱스 번호)와 flag(일치 여부) 변수에 값을 변경하여 저장하고 반복문 종료
					numId = i;
					flag = true;
					break;
				}
			}
			
			if(flag) { // 변수 flag가 참이면(입력된 도서의 ID와 저장되어 있는 도서 정보의 ID가 일치하면) 반복문을 종료하고, 거짓이면 '다시 입력해 주세요' 출력
				System.out.println("장바구니에 추가하겠습니까? Y | N");
				str = input.nextLine(); // 장바구니에 도서 추가 여부를 위한 입력값을 받음
				
				if(str.toUpperCase().equals("Y")) { // 입력값을 대문자로 변경하여 Y이면 '도서가 장바구니에 추가되었습니다.' 출력
					System.out.println(book[numId][0] + "도서가 장바구니에 추가되었습니다.");
				}
				
				quit = true;
				
			} else
				System.out.println("다시 입력해 주세요");
		}
	}

	public static void menuCartRemoveItemCount() { // 장바구니의 항목 수량 줄이는 메서드
		System.out.println("5. 장바구니의 항목 수량 줄이기");
	}

	public static void menuCartRemoveItem() { // 장바구니의 항목 삭제하는 메서드
		System.out.println("6. 장바구니의 항목 삭제하기");
	}

	public static void menuCartBill() { // 영수증 표시하는 메서드
		System.out.println("7. 영수증 표시하기");
	}

	public static void menuExit() {  // 종료하는 메서드
		System.out.println("8. 종료");
	}

	public static void BookList(String[][] book) { // 도서 정보를 저장하는 메서드

		book[0][0] = "ISBN1234";
		book[0][1] = "쉽게 배우는 JSP 웹 프로그래밍";
		book[0][2] = "27000"; // 27,000
		book[0][3] = "송미영";
		book[0][4] = "단계별로 쇼핑몰을 구현하며 배우는 JSP 웹 프로그래밍 ";
		book[0][5] = "IT전문서";
		book[0][6] = "2018/10/08";

		book[1][0] = "ISBN1235";
		book[1][1] = "안드로이드 프로그래밍";
		book[1][2] = "33000"; // 33,000
		book[1][3] = "우재남";
		book[1][4] = "실습 단계별 명쾌한 멘토링!";
		book[1][5] = "IT전문서";
		book[1][6] = "2022/01/22";

		book[2][0] = "ISBN1236";
		book[2][1] = "스크래치";
		book[2][2] = "22000"; // 22,000
		book[2][3] = "고광일";
		book[2][4] = "컴퓨팅 사고력을 키우는 블록 코딩";
		book[2][5] = "컴퓨터입문";
		book[2][6] = "2019/06/10";
	}

	public static void main(String[] args) {
		String[][] mbook = new String[NUM_BOOK][NUM_ITEM]; // 도서 정보를 저장할 mBook을 2차원 배열로 생성
		// PART2에서 작성한 내용
		Scanner input = new Scanner(System.in);

		System.out.print("당신의 이름을 입력하세요 : ");
		String userName = input.next();

		System.out.print("연락처를 입력하세요 : ");
		int userMobile = input.nextInt();

		String greeting = "Welcome to Shopping Mall";
		String tagline = "Welcome to Book Market!";

		boolean quit = false; // 종료 여부 설정 변수

		while (!quit) { // quit 변수가 true일 때까지 계속 반복			
			System.out.println("***************************************");
			System.out.println("\t" + greeting);
			System.out.println("\t" + tagline);

			/*
			 * 기존 메뉴 설명 주석 처리 System.out.println("***************************************");
			 * System.out.println("1. 고객 정보 확인하기 \t4. 바구니에 항목 추가하기");
			 * System.out.println("2. 장바구니 상품 목록 보기 \t5. 장바구니의 항목 수량 줄이기");
			 * System.out.println("3. 장바구니 비우기 \t6. 장바구니의 항목 삭제하기");
			 * System.out.println("7. 영수증 표시하기 \t8. 종료");
			 * System.out.println("***************************************");
			 */

			menuIntroduction(); // 메뉴 목록 출력 메서드 호출

			System.out.println("메뉴 번호를 선택해주세요 ");
			int n = input.nextInt();

//		System.out.println(n +"n번을 선택했습니다. ");

			if (n < 1 || n > 8) { // 메뉴 선택 번호가 1~8이 아니면 아래 문자열 출력
				System.out.println("1부터 8까지의 숫자를 입력하세요.");
			}

			else {
				switch (n) { // switch문을 이용하여 메뉴 선택 번호별 정보 출력
				case 1:
					/*
					 * 기존 내용 주석 처리 
					 * System.out.println("현재 고객 정보 : "); System.out.println("이름 " + userName + " 연락처 "+ userMobile); // 메뉴 번호가 1일 때 입력된 고객 이름과 연락처 출력
					 */
					menuGuestInfo(userName, userMobile);
					break;
				case 2:
//				System.out.println("장바구니 상품 목록 보기 : ");
					menuCartItemList();
					break;
				case 3:
//				System.out.println("장바구니 비우기: ");
					menuCartClear();
					break;
				case 4:
//				System.out.println("장바구니에 항목 추가하기 : ");
					menuCartAddItem(mbook);
					break;
				case 5:
//				System.out.println("5. 장바구니의 항목 수량 줄이기");
					menuCartRemoveItemCount();
					break;
				case 6:
//				System.out.println("6. 장바구니의 항목 삭제하기");
					menuCartRemoveItem();
					break;
				case 7:
//				System.out.println("7. 영수증 표시하기");
					menuCartBill();
					break;
				case 8:
//				System.out.println("8. 종료");
					menuExit();
					quit = true; // quit에 true를 넣어 반복문 종료 조건을 충족
					break;

				}
			}
		}
	}
}

 

+ Recent posts