DAY 16
•확장에서 getter and setter 설치하면 java 코드를 블록으로 선택해서 F1을 누른후 getter&setter를 이용해 메소드를 쉽게 만들 수 있음.
singleton : 전체 프로그램에서 객체가 하나뿐인 것
singleton 과 static의 공통점 : class 내에서 하나만 존재한다.
abstract class를 상속받는 class는 abstract method를 무조건 만들어서 override해야함.
abstract class는 하위 클래스 타입의 객체를 담는 변수 타입으로 사용가능함.
overriding 된 method 사용 가능.
Code
public class ExceptionEx {
public static void main(String[] args) {
int a = 10, b = 1;
int[] arr = {10, 20};
try {
// 예외가 발생할 수도 있는 명령문을 try안에
System.out.println(a/b); // ArithmeticException 발생
System.out.println(arr[3]); // ArrayIndexOutOfBoundsException 발생
}
catch (Exception e) {
System.out.println("뭔가 터졌다.");
}
// // catch 괄호 안쪽은, 처리할 예외의 종류를 쓴다.
// catch(ArithmeticException e) { // 산술연산 예외
// // a/b를 했을 때 발생할 수 있는 예외는
// // ArithmeticException 이므로, 여기서 예외가 처리된다.
// System.out.println("0으로 나눌 수 없음");
// }
// catch(ArrayIndexOutOfBoundsException e){
// System.out.println("배열 범위를 넘어섬");
// }
}
}
public class ExceptionEx02 {
public static void main(String[] args) /*throws Exception */{
try{
divide(10, 0);
}
catch(Exception e) {
e.printStackTrace();
System.out.println("0으로 나눌 수 없음");
}
finally {
// try나 catch구문의 return문에 있어도 실행된다.
System.out.println("예외 발생과 상관없이 실행");
}
}
public static void divide(int a, int b) throws Exception
{ // divide를 호출한 쪽에서 Exception을 처리하도록 함.(throws)
System.out.println(a/b);
}
}
미니 프로젝트를 위해 기능이나 데이터에 따라 폴더나 파일 분류해서 코드 작성하는 법 배움.
data 폴더에 각 필요한 데이터 입력
service 폴더에 서비스에 필요한 메서드 입력
main에서 실행

package data;
import java.util.Map;
public class StoreBasicInfo {
public String name;
public Double score;
public Integer min_order_price;
public Integer[] delivery_time;
// public Integer[] delivery_price;
public Map<String, Integer> delivery_price;
public StoreBasicInfo
(String name, Double score, Integer min_order_price, Integer[] delivery_time, Map<String, Integer>delivery_price) {
this.name = name;
this.score = score;
this.min_order_price = min_order_price;
this.delivery_time = delivery_time;
this.delivery_price = delivery_price;
}
@Override
public String toString(){
String str = "";
str += "가게이름 : " + name + " / 별점 : " + score + "\n";
str += "최소 주문 금액 : " + min_order_price + "원\n";
str += "배달시간 : " + delivery_time[0] + "~" + delivery_time[1] + "분\n";
str += "배달팁 : " + delivery_price.get("min") + "~" + delivery_price.get("max") + "원\n";
return str;
}
}
package data;
import java.util.ArrayList;
import java.util.List;
public class Store { // 정보 저장
public StoreBasicInfo basicInfo;
public StoreDetailInfo detailInfo;
public StoreBusinessInfo businessInfo;
public List<Menu>menus;
public List<Review> reviews;
public Store(StoreBasicInfo basicInfo, StoreDetailInfo detailInfo, StoreBusinessInfo businessInfo) {
this.basicInfo = basicInfo;
this.detailInfo = detailInfo;
this.businessInfo = businessInfo;
menus = new ArrayList<Menu>();
reviews = new ArrayList<Review>();
}
@Override
public String toString(){
return basicInfo.toString() + "\n" + detailInfo.toString() + "\n" + businessInfo.toString();
}
}
package serivce;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import data.Member;
import util.AESAlgorithm;
public class MemberService {
public static List <Member> memberList = new ArrayList<Member>();
public static Scanner scan = new Scanner(System.in);
public static Member loginMember = null; // Session
public static void addMasterMember()throws Exception{
memberList.add(new Member("admin", AESAlgorithm.Encrypt("1234"), "관리자", true));
}
public static void memberJoin() throws Exception {
System.out.println("========== 회원 가입 =========");
System.out.print("아이디 : ");
String id = scan.nextLine();
if(isDuplicatedId(id)) {
System.out.println(id + "은(는) 이미 가입된 아이디 입니다.");
return;
}
System.out.print("비밀번호 : ");
String pwd = AESAlgorithm.Encrypt(scan.nextLine());
System.out.print("가입자 명 : ");
String name = scan.nextLine();
System.out.println("관리인 : 0 / 일반회원 : 1");
Integer type = scan.nextInt();
scan.nextLine();
memberList.add(new Member(id, pwd, name, type == 0));
System.out.println("회원 등록이 완료되었습니다.");
}
public static void logout(){
System.out.println("로그아웃 되었습니다.");
loginMember = null;
}
public static void login() throws Exception{
System.out.println("========== 로그인 =========");
System.out.print("아이디 : ");
String id = scan.nextLine();
System.out.print("비밀번호 : ");
String pwd = AESAlgorithm.Encrypt(scan.nextLine());
for(Member m : memberList) {
if(m.id.equals(id) && m.pwd.equals(pwd)){
loginMember = m;
}
}
if(loginMember == null) {
System.out.println("아이디 또는 비밀번호가 잘못되거나 없는 회원입니다.");
}
}
public static void showMemberList(){
if(memberList.size()==0) {
System.out.println("등록된 회원이 없습니다.");
}
else {
for(int i=0; i<memberList.size(); i++) {
System.out.println(memberList.get(i));}
}
}
public static Boolean isDuplicatedId(String id){
for(Member m : memberList) {
if(id.equals(m.id)){
return true;
}
}
return false; // 리스트를 모두 조회하고나서 여기로 나올 수 있다면
// 중복 아이디가 없다는 것
}
}
package serivce;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import data.Menu;
import data.Review;
import data.Store;
import data.StoreBasicInfo;
import data.StoreBusinessInfo;
import data.StoreDetailInfo;
public class StoreService { // 기능 컨트롤
public static Scanner scan = new Scanner(System.in);
public static Store selectedStore =null;
public static List<Store> storeList = new ArrayList<Store>();
public static void showStoreList(){ // main에서 기능이관
if(storeList.size() == 0){
System.out.println("등록된 가게가 없습니다.`");
}
else {
for(Store s : storeList) {
System.out.println(s.basicInfo);
}
}
}
public static void addStore(/*Store store*/) { // main에서 기능이관
Integer [] deliveryTime = {0, 0};
Map<String, Integer> dPrice = new HashMap<String, Integer>();
Map<String, String> openClose = new HashMap<String, String>();
// dPrice.put("min", 2000);
// dPrice.put("max", 3000);
// openClose.put("open", "9시");
// openClose.put("close", "오후 10시");
System.out.println("========== 가게 기본 정보 ==========");
System.out.print("상호 명 : ");
String store_name = scan.nextLine();
System.out.print("최소 주문 금액 : ");
Integer min_order_price = scan.nextInt();
scan.nextLine();
System.out.print("최소 배달시간 (분) : ");
deliveryTime[0] = scan.nextInt();
scan.nextLine();
System.out.print("최대 배달시간 (분) : ");
deliveryTime[1] = scan.nextInt();
scan.nextLine();
System.out.print("배달 팁 최소 : ");
Integer dpriceMin = scan.nextInt();
scan.nextLine();
System.out.print("배달 팁 최대 : ");
Integer dpriceMax = scan.nextInt();
scan.nextLine();
dPrice.put("min", dpriceMin);
dPrice.put("max", dpriceMax);
System.out.println("========= 가게 상세 정보 ==========");
System.out.print("가게 소개 글 : ");
String introduce = scan.nextLine();
System.out.print("가게 공지사항 : ");
String notice = scan.nextLine();
System.out.print("개점 시간 (00:00) : ");
String open_time = scan.nextLine();
System.out.print("폐점 시간 (00:00) : ");
String close_time = scan.nextLine();
openClose.put("open", open_time);
openClose.put("close", close_time);
System.out.print("휴무일 : ");
String off = scan.nextLine();
System.out.print("가게 전화번호 : ");
String phone = scan.nextLine();
System.out.print("배달 가능 지역 : ");
String dArea = scan.nextLine();
System.out.println("========= 사업자 정보 ==========");
System.out.print("대표자 :");
String owner = scan.nextLine();
System.out.print("사업자 명 :");
String store = scan.nextLine();
System.out.print("사업자 주소 :");
String address = scan.nextLine();
System.out.print("사업자 번호 :");
String regNo = scan.nextLine();
Store s = new Store(
new StoreBasicInfo(store_name, 0.0, min_order_price, deliveryTime, dPrice),
new StoreDetailInfo(introduce, notice, openClose, off, phone, dArea),
new StoreBusinessInfo(owner, store, address, regNo)
);
storeList.add(s);
}
public static void selectStore(){
System.out.print("가게 선택 (0 ~ " + (storeList.size()-1) + ") : ");
Integer sel = scan.nextInt();
scan.nextLine();
if(sel<0 || sel >= storeList.size()) {
System.out.println("잘못된 번호 선택입니다.");
return;
}
selectedStore = storeList.get(sel);
System.out.println(selectedStore.basicInfo);
}
public static void showStoreMenus(){ // Menu에서 기능 이관
if (selectedStore == null) {
System.out.println("먼저 가게를 선택하세요.");
return;
}
if(selectedStore.menus.size() == 0){
System.out.println("등록된 메뉴 없음");
}
else {
for(int i=0; i<selectedStore.menus.size();i++) {
System.out.println(i + "번 메뉴\n" + selectedStore.menus.get(i));
}
}
}
public static void addStoreMenu() { // Menu에서 기능 이
if (selectedStore == null) {
System.out.println("먼저 가게를 선택하세요.");
return;
}
System.out.print("메뉴 이미지 : ");
String img = scan.nextLine();
System.out.print("메뉴 이름 : ");
String name = scan.nextLine();
System.out.print("메뉴 설명 : ");
String desc = scan.nextLine();
System.out.print("메뉴 가격 : ");
Integer price = scan.nextInt();
scan.nextLine();
selectedStore.menus.add(new Menu(img, name, desc, price));
}
public static void showStoreReviews(){ // Store에서 기능이관
if (selectedStore == null) {
System.out.println("먼저 가게를 선택하세요.");
return;
}
if(selectedStore.reviews.size() == 0){
System.out.println("등록된 리뷰 없음");
}
else {
for(int i=0; i<selectedStore.reviews.size();i++) {
System.out.println(i + "번 리뷰\n" + selectedStore.reviews.get(i));
}
}
}
public static void addStoreReview() { // Store에서 기능이관
if (selectedStore == null) {
System.out.println("먼저 가게를 선택하세요.");
return;
}
System.out.print("작성자 : ");
String id = scan.nextLine();
System.out.print("평점 (1~5) : ");
Integer score = scan.nextInt();
scan.nextLine();
System.out.print("리뷰 내용 : ");
String content = scan.nextLine();
selectedStore.reviews.add(new Review(id, score, content));
int sum = 0;
for(Review r : selectedStore.reviews) {
sum += r.score;
}
selectedStore.basicInfo.score = sum/(double)selectedStore.reviews.size();
}
}
import java.util.Scanner;
import serivce.MemberService;
import serivce.StoreService;
public class Main { // 기능 실행
public static Scanner scan = new Scanner(System.in);
public static void main(String[] args) throws Exception{
MemberService.addMasterMember(); // 마스터 계정 추가
while(true) {
System.out.print("1.관리자 / 2. 일반 사용자 / 0.종료 :");
Integer sel = scan.nextInt();
scan.nextLine();
if (sel ==0) {
break;
}
else if (sel ==1) {
adminMode();
}
else if (sel ==2) {
normalMode();
}
}
}
public static void normalMode() throws Exception{
while(true) {
String storeName ="";
if(StoreService.selectedStore != null) {
storeName = StoreService.selectedStore.basicInfo.name;
}
else {
System.out.println("선택된 가게 없음");
}
String loginInfo ="";
if (MemberService.loginMember != null) {
loginInfo = MemberService.loginMember.name + "(" + MemberService.loginMember.id + ") 님";
System.out.println("99.로그아웃");
}
else {
loginInfo = "비회원";
System.out.println("98. 회원가입, 97.로그인");
}
System.out.println("## 회원 정보 : " + loginInfo);
System.out.println("## 선택 중인 가게 : " + storeName);
System.out.println("1. 가게 목록 보기");
System.out.println("2. 가게 선택");
System.out.println("3. 메뉴 목록 보기");
System.out.println("4. 리뷰 보기");
System.out.println("5. 리뷰등록");
System.out.println("0. 종료");
System.out.print("선택 (0-5) : ");
Integer sel = scan.nextInt();
scan.nextLine();
if (sel == 0) {
break;
}
else if(sel == 1) {
StoreService.showStoreList();
}
else if(sel == 2) {
StoreService.selectStore();
}
else if(sel == 3) {
StoreService.showStoreMenus();
}
else if(sel == 4) {
StoreService.showStoreReviews();
}
else if(sel == 5) {
StoreService.addStoreReview();
}
else if(sel == 99 && MemberService.loginMember != null) {
MemberService.logout();
}
else if(sel == 98 && MemberService.loginMember == null) {
MemberService.memberJoin();
}
else if(sel == 97 && MemberService.loginMember == null) {
MemberService.login();
}
else {
break;
}
}
}
public static void adminMode() throws Exception {
MemberService.login();
if(MemberService.loginMember != null) {
if(MemberService.loginMember.isAdmin == false) {
System.out.println("관리자 전용 입니다.");
return; // 로그인 했으나, 관리자가 아님
}
}
else {
return; // 로그인 실패
}
while(true) {
String storeName ="";
if (StoreService.selectedStore != null) {
storeName = StoreService.selectedStore.basicInfo.name;
}
else {
storeName = "선택한 가게 없음";
}
System.out.println("## 선택 중인 가게 : " + storeName);
System.out.println("1. 가게 목록 보기");
System.out.println("2. 가게 추가");
System.out.println("3. 가게 선택");
System.out.println("4. 메뉴 추가");
System.out.println("5. 메뉴 목록 보기");
System.out.println("6. 리뷰 보기");
System.out.println("0. 종료");
System.out.print("선택 (0-6) : ");
Integer sel = scan.nextInt();
scan.nextLine();
if (sel == 0) {
break;
}
else if(sel == 1) {
StoreService.showStoreList();
}
else if(sel == 2) {
StoreService.addStore();
}
else if(sel == 3) {
StoreService.selectStore();
}
else if(sel == 4) {
StoreService.addStoreMenu();
}
else if(sel == 5) {
StoreService.showStoreMenus();
}
else if(sel == 6) {
StoreService.showStoreReviews();
}
}
}
}
package util;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.apache.tomcat.util.codec.binary.Base64;
public class AESAlgorithm {
public static String Decrypt(String text) throws Exception{
String key = "pwd!@#$";
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
byte[] keyBytes= new byte[16];
byte[] b= key.getBytes("UTF-8");
int len= b.length;
if (len > keyBytes.length) len = keyBytes.length;
System.arraycopy(b, 0, keyBytes, 0, len);
SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");
IvParameterSpec ivSpec = new IvParameterSpec(keyBytes);
cipher.init(Cipher.DECRYPT_MODE,keySpec,ivSpec);
byte [] results = cipher.doFinal(Base64.decodeBase64(text));
return new String(results,"UTF-8");
}
public static String Encrypt(String text) throws Exception{
String key = "pwd!@#$";
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
byte[] keyBytes= new byte[16];
byte[] b= key.getBytes("UTF-8");
int len= b.length;
if (len > keyBytes.length) len = keyBytes.length;
System.arraycopy(b, 0, keyBytes, 0, len);
SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");
IvParameterSpec ivSpec = new IvParameterSpec(keyBytes);
cipher.init(Cipher.ENCRYPT_MODE,keySpec,ivSpec);
byte[] results = cipher.doFinal(text.getBytes("UTF-8"));
return Base64.encodeBase64String(results);
}
}