-
[과제] 키오스크 필수 Lv5내일배움캠프/과제 2025. 3. 13. 15:57
✅ Lv5. 캡슐화 적용하기
1️⃣ 과제 조건
- MenuItem, Menu 그리고 Kiosk 클래스의 필드에 직접 접근하지 못하도록 설정합니다.
- Getter와 Setter 메서드를 사용해 데이터를 관리합니다.
2️⃣ 구현 포인트
1. 사용자의 입력을 관리하기 위한 InputHandler 생성
public class InputHandler { public int getUserInput(BufferedReader br, int maxOption) throws IOException { // 반복문 while (true) { try { System.out.print("번호를 선택해주세요 : "); int input = Integer.parseInt(br.readLine()); // 입력받은 값 parsing if (input >= 0 && input <= maxOption) { // 유효한 값이면 return return input; } else { System.out.println("\n! 올바른 번호를 입력해주세요 !\n"); } } catch (NumberFormatException ignored) { System.out.println("\n! 올바른 번호를 입력해주세요 !\n"); } } } }
2. 각 기능별 함수 분리
- Kiosk의 start() 에 많은 로직들을 각 함수별로 분리
// MAIN MENU 목록 출력 함수 private void printMainMenu() { System.out.println("\n[ MAIN MENU ]"); int i = 1; for (Menu menu : menuList) { System.out.println(i++ + ". " + menu.getCategory()); } System.out.println("0. 종료\n"); } // 메뉴 선택 후 process private void processMenuSelection(BufferedReader br, Menu menu) throws IOException { System.out.printf("\n[ %s MENU ]\n", menu.getCategory().toUpperCase()); // 선택한 메뉴 출력 menu.printMenuItemList(); // 선택한 메뉴의 menuItem List 출력 int itemNo = inputHandler.getUserInput(br, menu.getMenuItemsSize()); // 입력받기 if (itemNo != 0) { menu.printMenuItemDetails(itemNo - 1); // menuItem Detail 출력 } } public void printMenuItemList() { for (int i = 0; i < menuItems.size(); i++) { System.out.println((i + 1) + ". " + menuItems.get(i)); } System.out.println("0. 뒤로가기\n"); } // menuItem detail 출력 public void printMenuItemDetails(int index) { MenuItem item = menuItems.get(index); System.out.printf("선택한 메뉴 : %s | 가격 : W %.1f | 설명 : %s\n", item.getMenuNm(), item.getPrice(), item.getDesc()); }
3️⃣ 최종 코드
1. Main
import java.util.ArrayList; import java.util.List; public class Main { public static void main(String[] args) { List<Menu> menuList = new ArrayList<>(); // Burgers menuList.add(new Menu("Burgers", List.of( new MenuItem("ShackBurger", 6.9, "토마토, 양상추, 쉑소스가 토핑된 치즈버거"), new MenuItem("SmokeShack", 8.9, "베이컨, 체리 페퍼에 쉑소스가 토핑된 치즈버거"), new MenuItem("Cheeseburger", 6.9, "포테이토 번과 비프패티, 치즈가 토핑된 치즈버거"), new MenuItem("Hamburger", 5.4, "비프패티를 기반으로 야채가 들어간 기본버거") ))); // Drinks menuList.add(new Menu("Drinks", List.of( new MenuItem("Coke", 2.5, "탄산이 가득한 코카콜라"), new MenuItem("Cider", 2.5, "청량미 넘치는 사이다"), new MenuItem("Lemon juice", 3.0, "생과일 레몬이 들어간 레몬 쥬스"), new MenuItem("PowerAde", 3.0, "수분을 보충시켜 줄 파워에이드") ))); // Desserts menuList.add(new Menu("Desserts", List.of( new MenuItem("Cheese Cake", 5.0, "꾸덕한 치즈가 들어간 치즈 케이크"), new MenuItem("Chocolate cake", 5.5, "초코가 흘러내리는 달콤한 초콜릿 케이크"), new MenuItem("IceCream", 3.0, "시원한 아이스크림"), new MenuItem("Cookie", 2.0, "갓 구운 바삭한 쿠키") ))); new Kiosk(menuList).start(); } }
2. Menu
import java.util.List; public class Menu { private final String category; // 카테고리 private final List<MenuItem> menuItems; // menu Item 목록 public Menu(String category, List<MenuItem> menuItems) { this.category = category; this.menuItems = menuItems; } public String getCategory() { return category; } public int getMenuItemsSize() { return menuItems.size(); } // MenuItem 목록 출력 public void printMenuItemList() { for (int i = 0; i < menuItems.size(); i++) { System.out.println((i + 1) + ". " + menuItems.get(i)); } System.out.println("0. 뒤로가기\n"); } // menuItem detail 출력 public void printMenuItemDetails(int index) { MenuItem item = menuItems.get(index); System.out.printf("선택한 메뉴 : %s | 가격 : W %.1f | 설명 : %s\n", item.getMenuNm(), item.getPrice(), item.getDesc()); } }
3. MenuItem
public class MenuItem { private final String menuNm; // 메뉴명 private final double price; // 가격 private final String desc; // 설명 public MenuItem(String menuNm, double price, String desc) { this.menuNm = menuNm; this.price = price; this.desc = desc; } public String getMenuNm() { return menuNm; } public double getPrice() { return price; } public String getDesc() { return desc; } @Override public String toString() { return String.format("%-13s | W %-4.1f | %s", menuNm, price, desc); } }
4. InputHandler
import java.io.BufferedReader; import java.io.IOException; public class InputHandler { public int getUserInput(BufferedReader br, int maxOption) throws IOException { // 반복문 while (true) { try { System.out.print("번호를 선택해주세요 : "); int input = Integer.parseInt(br.readLine()); // 입력받은 값 parsing if (input >= 0 && input <= maxOption) { // 유효한 값이면 return return input; } else { System.out.println("\n! 올바른 번호를 입력해주세요 !\n"); } } catch (NumberFormatException ignored) { System.out.println("\n! 올바른 번호를 입력해주세요 !\n"); } } } }
5. Kiosk
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.List; public class Kiosk { private final List<Menu> menuList; // 메뉴 목록 private final InputHandler inputHandler; // inputHandler public Kiosk(List<Menu> menuList) { this.menuList = menuList; this.inputHandler = new InputHandler(); } public void start() { try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) { while (true) { this.printMainMenu(); // MAIN MENU 목록 출력 함수 실행 int menuNo = inputHandler.getUserInput(br, menuList.size()); // inputHandler 실행 if (menuNo == 0) { // 0 이면 프로그램 종료 break; } processMenuSelection(br, menuList.get(menuNo - 1)); // 선택한 Menu 진행 } } catch (IOException e) { System.out.println("\n! 에러가 발생했습니다 !\n"); } System.out.println("\n프로그램을 종료합니다."); } // MAIN MENU 목록 출력 함수 private void printMainMenu() { System.out.println("\n[ MAIN MENU ]"); int i = 1; for (Menu menu : menuList) { System.out.println(i++ + ". " + menu.getCategory()); } System.out.println("0. 종료\n"); } // 메뉴 선택 후 process private void processMenuSelection(BufferedReader br, Menu menu) throws IOException { System.out.printf("\n[ %s MENU ]\n", menu.getCategory().toUpperCase()); // 선택한 메뉴 출력 menu.printMenuItemList(); // 선택한 메뉴의 menuItem List 출력 int itemNo = inputHandler.getUserInput(br, menu.getMenuItemsSize()); // 입력받기 if (itemNo != 0) { menu.printMenuItemDetails(itemNo - 1); // menuItem Detail 출력 } } }
'내일배움캠프 > 과제' 카테고리의 다른 글
[과제] 키오스크 도전 Lv2 (2) 2025.03.13 [과제] 키오스크 도전 Lv1 (0) 2025.03.13 [과제] 키오스크 필수 Lv4 (0) 2025.03.13 [과제] 키오스크 필수 Lv3 (0) 2025.03.13 [과제] 키오스크 필수 Lv2 (1) 2025.03.13