Menu
Coddy logo textTech

在庫の確認

CoddyのGOジャーニー「論理とフロー」セクションの一部 — レッスン 46/68。

challenge icon

チャレンジ

簡単

在庫管理システムのために、製品の数量を安全に取得し、製品が存在しない場合を処理する在庫確認機能を実装してください。このチャレンジは、前回のレッスンの在庫の基礎に基づいて構築されており、在庫クエリのエラー処理を追加します。

2つの入力を受け取ります:

  • "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"

あなたのタスクは以下の通りです:

  1. 前回のレッスンと同じ、Price (float64) と Quantity (int) フィールドを持つ Product 構造体を使用します。
  2. 最初の入力をカンマで分割して、個々の製品エントリを取得し、解析します。
  3. 各製品エントリについて、コロンで分割して製品名、価格、数量を取得します。
  4. 価格の文字列を float64 に、数量の文字列を int に変換します。
  5. 解析した製品データを使用して inventory マップを作成し、データを格納します。
  6. 在庫マップと製品名をパラメータとして受け取り、(int, error) を返す checkStock という関数を作成します:
    • 製品が在庫に存在する場合は、その数量と nil を返します。
    • 製品が存在しない場合は、0 と "product not found: [product_name]" というメッセージを持つエラーを返します。
  7. 2番目の入力をカンマで分割して、確認する製品のリストを取得し、解析します。
  8. 在庫確認のヘッダーを表示します:"Stock Check Results:"
  9. 確認リストの各製品について、checkStock 関数を呼び出し、結果を表示します:
    • エラーがない場合:"[product_name]: [quantity] units in stock"
    • エラーがある場合:"[product_name]: Error - [error_message]"
  10. 要約統計をカウントして表示します:
    • "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]"
  11. 見つかった製品の合計在庫を表示します:
    • "Total stock for found products: [sum_of_quantities_for_existing_products] units"
  12. 不足している製品をリストします:
    • 不足している製品がある場合:"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")
}

論理とフローのすべてのレッスン