과제/키오스크

kiosk 과제 lv4-인터페이스 구현

crablo 2024. 3. 13. 11:25
728x90

kiosk 과제 lv3까지는 주문시 메뉴선택기능만 있었는데

lv4부터는 주문시 가격차감 및 잔액 표시 기능까지 추가하였다.

lv3까지와 마찬가지로 클래스별로 기능을 나눴다.

먼저 작성한 파일은 Food.kt 파일이고, 인터페이스(바디가 없는 메서드들의 모음)로 구현했다.

package com.ellycrab.kiosklv4

interface Food {

    //대분류 메뉴
    val categoryName:String
    //소분류 메뉴
    val foodOptions:List<Pair<String,Double>>

    
    fun displayOptions()
    fun orderItem(choice:Int):Pair<String,Double>?
}

Sandwiches   Wraps  Salads 클래스에서는 Food클래스를 상속 받는다.

package com.ellycrab.kiosklv4

class Sandwiches:Food {
    
    override val categoryName: String = "Sandwiches"
    
    override val foodOptions: List<Pair<String, Double>> = listOf(
        "Egg Slice" to 3000.0,
        "Italian BMT" to 6500.0,
        "Chicken Bacon Avocado" to 7000.0,
        "Rotisserie Barbecue" to 8000.0,
        "Shrimp" to 6500.0,
        "Roasted Chicken" to 8000.0
    )

   

    override fun displayOptions() {
        println("$categoryName 옵션:")
        foodOptions.forEachIndexed { index, (item, price) ->
            println("${index + 1}. $item - Price: $price")
        }
    }

    override fun orderItem(choice: Int): Pair<String, Double>? {
        if (choice in 1..foodOptions.size) {
            return foodOptions[choice - 1]
        }
        return null
    }
}
package com.ellycrab.kiosklv4

class Salads : Food {
    override val foodOptions: List<Pair<String, Double>> = listOf(
        "Egg Slice" to 3000.0,
        "Spicy Shrimp" to 4000.0,
        "Spicy Italian" to 5000.0,
        "Steak Cheese" to 7000.0,
        "Chicken Bacon" to 10000.0,
        "KBBQ" to 5000.0
    )
    override val categoryName: String = "Salads"

    override fun displayOptions() {
        println("$categoryName 옵션:")
        foodOptions.forEachIndexed { index, (item, price) ->
            println("${index + 1}. $item - Price: $price")
        }
    }

    override fun orderItem(choice: Int): Pair<String, Double>? {
        if (choice in 1..foodOptions.size) {
            return foodOptions[choice - 1]
        }
        return null
    }
}
package com.ellycrab.kiosklv4

class Wraps:Food {

    override val foodOptions: List<Pair<String, Double>>
        = listOf(
        "Steak Wrap" to 4500.0,
        "Egg Mayo" to 5000.0,
        "Chicken Bacon" to 6000.0
        )
    override val categoryName: String = "Wraps"

    override fun displayOptions() {
        println("$categoryName 옵션:")
        foodOptions.forEachIndexed { index, (item, price) ->
            println("${index + 1}. $item - Price: $price")
        }
    }
    override fun orderItem(choice: Int): Pair<String, Double>? {
        if (choice in 1..foodOptions.size) {
            return foodOptions[choice - 1]
        }
        return null
    }
}

각각의 음식 메뉴 클래스들은 Food.kt메서드를 그대로 상속받아서 각각의 타입에 맞게 값을 세팅해주었다.

마지막으로 Custormer.kt 클래스를 따로 만들어 

주문했을때 돈이 차감되고 , 입금하는 기능을 설계했다.

package com.ellycrab.kiosklv4

class Customer(var balance:Double) {
    private val orders = mutableListOf<Pair<String,Double>>()

    fun displayBalance(){
        println("현재 잔액: $balance")
    }

    //주문
    fun placeOrder(food:Food, choice:Int){
        var orderedItem = food.orderItem(choice)
        if(orderedItem != null){
            orders.add(orderedItem)
            balance -= orderedItem.second
            println("주문: ${orderedItem.first} - 가격: ${orderedItem.second}")
            displayBalance()
        }else{
            println("유효하지 않은 선택입니다. 다시 선택해주세요.")
        }
    }
    //현재 주문한게 뭔지 나타내기
    fun displayOrders() {
        println("당신의 주문입니다.:")
        orders.forEachIndexed { index, (item, price) ->
            println("${index + 1}. $item - 가격: $price")
        }
        displayBalance()
    }
    //입금하기
    fun deposit(amount:Double){
        balance += amount
        println("입금 성공!! 현재잔액:$balance")
    }
}

마지막으로 Main.kt에서
 주문했을때,
선택된 메뉴에따라 주문을 출력 및 잔액 출력 기능을 설계했다.


import com.ellycrab.kiosklv4.Customer
import com.ellycrab.kiosklv4.Food
import com.ellycrab.kiosklv4.Salads
import com.ellycrab.kiosklv4.Sandwiches
import com.ellycrab.kiosklv4.Wraps
import java.lang.Exception

fun main(){
    //초기 자본 세팅
    val customer = Customer(20000.0)
    val menus: List<Food> = init()




    while(true){
        println("서브웨이 메뉴:")
        println("1. Salads(Egg Slice, Spicy Shrimp, Spicy Italian, Steak Cheese, Chicken Bacon, KBBQ)")
        println("2. Sandwiches(Egg Slice, Italian BMT, Chicken Bacon Avocado, Rotisserie Barbecue, Shrimp, Roasted Chicken)")
        println("3. Wraps(Steak Wrap, Egg Mayo,Chicken Bacon)")
        println("0. 프로그램 종료")
        println("80. 입금")

        print("1~3,80 번호 중 하나를 선택해주세요: ")

        when (val categoryChoice = readLine()?.toIntOrNull()) {
            in 1..3 -> {
                val menuCategory = menus[categoryChoice?.minus(1)!!]
                orderSebuItem(menuCategory, customer.balance)
            }
            0 -> {
                println("프로그램을 종료합니다.")
                return
            }
            80 -> {
                print("입금할 금액을 입력하세요: ")
                val depositAmount = readLine()?.toDoubleOrNull()
                if (depositAmount != null) {
                    customer.deposit(depositAmount)
                } else {
                    println("잘못된 입력. 유효한 금액을 입력하세요.")
                }
            }
            else -> {
                // 숫자 이외에 다른 것을 선택했을 때
                println("유효하지 않은 카테고리 선택입니다.")
            }
        }
    }
}

fun orderSebuItem(menuCategory: Food, customerBalance: Double) {
    menuCategory.displayOptions()
    print("세부 메뉴를 선택해주세요. (1-${menuCategory.foodOptions.size}): ")
    val itemChoice = readLine()?.toIntOrNull()

    itemChoice?.let {
        val orderedItem = menuCategory.orderItem(it)

        orderedItem?.let {
            if (customerBalance >= it.second) {
                // 잔액충분
                println("당신의 주문입니다 => $it")
                println("주문 후 잔액: ${customerBalance - it.second}")
            } else {
                // 잔액부족
                println("잔액이 부족합니다. 주문을 완료할 수 없습니다.")
            }
        } ?: println("유효하지 않은 세부 선택입니다.")
    } ?: println("유효하지 않은 입력입니다.")
}

fun init(): List<Food> {
    return listOf(Salads(), Sandwiches(), Wraps())
}
728x90

'과제 > 키오스크' 카테고리의 다른 글

kiosk lv3-추상클래스 구현  (0) 2024.03.12
kiosk 과제 lv2  (0) 2024.03.11
kiosk 과제 lv0,1  (0) 2024.03.11