'한빛아카데미 - 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;
			}
		}
	}
}

 

+ Recent posts