재고 확인하기
Coddy GO 여정의 로직 & 흐름 섹션에 포함된 레슨 — 68개 중 46번째.
챌린지
쉬움재고 관리 시스템을 위해 제품 수량을 안전하게 검색하고 제품이 존재하지 않는 경우를 처리하는 재고 확인 함수를 구현하세요. 이 챌린지는 이전 레슨의 재고 기초를 바탕으로 하며, 재고 쿼리에 대한 에러 처리를 추가합니다.
두 개의 입력을 받게 됩니다:
"product1:price1:quantity1,product2:price2:quantity2,product3:price3:quantity3"형식의 기존 재고 데이터를 포함하는 문자열 (예:"Laptop:999.99:5,Mouse:25.50:15,Keyboard:75.00:8")"product1,product2,product3"형식의 재고 확인 요청을 포함하는 문자열 (예:"Mouse,Tablet,Keyboard")
당신의 과제는 다음과 같습니다:
- 이전 레슨과 동일하게
Price(float64) 및Quantity(int) 필드를 가진Product구조체를 사용합니다. - 첫 번째 입력을 쉼표로 분할하여 개별 제품 항목을 가져와 파싱합니다.
- 각 제품 항목에 대해 콜론을 기준으로 분할하여 제품 이름, 가격 및 수량을 가져옵니다.
- 가격 문자열을 float64로, 수량 문자열을 int로 변환합니다.
- 파싱된 제품 데이터로
inventory맵을 생성하고 채웁니다. - 재고 맵과 제품 이름을 매개변수로 받고 (int, error)를 반환하는
checkStock이라는 함수를 만듭니다:- 제품이 재고에 존재하면 수량과 nil을 반환합니다.
- 제품이 존재하지 않으면 0과
"product not found: [product_name]"메시지가 포함된 에러를 반환합니다.
- 두 번째 입력을 쉼표로 분할하여 확인할 제품 목록을 가져와 파싱합니다.
- 재고 확인 헤더를 표시합니다:
"Stock Check Results:" - 확인 목록의 각 제품에 대해
checkStock함수를 호출하고 결과를 표시합니다:- 에러가 없는 경우:
"[product_name]: [quantity] units in stock" - 에러가 있는 경우:
"[product_name]: Error - [error_message]"
- 에러가 없는 경우:
- 요약 통계를 계산하고 표시합니다:
"Check Summary:""Products checked: [total_number_of_products_checked]""Products found: [number_of_products_that_exist]""Products not found: [number_of_products_that_dont_exist]"
- 찾은 제품의 총 재고를 표시합니다:
"Total stock for found products: [sum_of_quantities_for_existing_products] units"
- 누락된 제품을 나열합니다:
- 누락된 제품이 있는 경우:
"Missing products: [comma_separated_list_of_missing_products]" - 누락된 제품이 없는 경우:
"All requested products are available"
- 누락된 제품이 있는 경우:
입력 문자열을 분할하기 위해 strings 패키지를, 문자열을 숫자로 변환하기 위해 strconv 패키지를, 에러 메시지를 생성하기 위해 errors 패키지를, 그리고 형식화된 출력을 위해 fmt 패키지를 사용하세요. 이 챌린지는 재고 관리 시스템의 기본 패턴인 적절한 에러 처리를 통한 안전한 데이터 검색 구현 방법을 보여줍니다.
직접 해보기
package main
import (
"bufio"
"fmt"
"os"
"sort"
"strconv"
"strings"
)
// Define the Product struct
type Product struct {
Price float64
Quantity int
}
func main() {
// Read input using bufio.Scanner to handle spaces properly
scanner := bufio.NewScanner(os.Stdin)
scanner.Scan()
storeInfo := scanner.Text()
scanner.Scan()
productData := scanner.Text()
// 1. Parse store information (split by comma)
storeInfoParts := strings.Split(storeInfo, ",")
storeName := ""
location := ""
if len(storeInfoParts) >= 2 {
storeName = storeInfoParts[0]
location = storeInfoParts[1]
}
// 2. Parse product data (split by comma, then by colon for each product)
productEntries := strings.Split(productData, ",")
// 3. Create inventory map
inventory := make(map[string]Product)
// 4. Convert strings to appropriate types and populate inventory
for _, entry := range productEntries {
parts := strings.Split(entry, ":")
if len(parts) >= 3 {
productName := parts[0]
price, _ := strconv.ParseFloat(parts[1], 64)
quantity, _ := strconv.Atoi(parts[2])
inventory[productName] = Product{
Price: price,
Quantity: quantity,
}
}
}
// 5. Display store information
fmt.Printf("=== %s Inventory System ===\n", storeName)
fmt.Printf("Location: %s\n", location)
fmt.Printf("Inventory initialized with %d products\n", len(inventory))
// 6. Display current inventory (sorted alphabetically)
fmt.Println("Current Inventory:")
var productNames []string
for name := range inventory {
productNames = append(productNames, name)
}
sort.Strings(productNames)
for _, name := range productNames {
product := inventory[name]
fmt.Printf("- %s: $%.2f (Stock: %d)\n", name, product.Price, product.Quantity)
}
// 7. Calculate and display inventory statistics
totalProducts := len(inventory)
totalItems := 0
totalValue := 0.0
for _, product := range inventory {
totalItems += product.Quantity
totalValue += product.Price * float64(product.Quantity)
}
fmt.Println("Inventory Statistics:")
fmt.Printf("Total Products: %d\n", totalProducts)
fmt.Printf("Total Items in Stock: %d\n", totalItems)
fmt.Printf("Total Inventory Value: $%.2f\n", totalValue)
// 8. Display system status
fmt.Println("System Status: Ready")
fmt.Println("Inventory management system initialized successfully")
}