全体をまとめる
CoddyのGOジャーニー「論理とフロー」セクションの一部 — レッスン 25/68。
チャレンジ
簡単これまでのレッスンで構築したすべての機能を統合する包括的なメインプログラムを作成し、在庫管理システムを完成させましょう。この最終チャレンジでは、在庫の初期化、在庫確認、商品の追加、在庫の更新、およびレポート生成を、メニュー駆動型のナビゲーションを備えた完全なコマンドラインインターフェースに統合します。
3つの入力を受け取ります:
"product1:price1:quantity1,product2:price2:quantity2,product3:price3:quantity3"という形式の初期在庫データを含む文字列(例:"Laptop:999.99:5,Mouse:25.50:15,Keyboard:75.00:8")"operation1,operation2,operation3"という形式のメニュー操作のシーケンスを含む文字列。操作は"check"、"add"、"update"、"report"、または"exit"です(例:"check,add,update,report,exit")"param1|param2|param3"という形式の操作パラメータを含む文字列。各パラメータは同じ位置にある操作に対応します(例:"Mouse|Monitor:299.99:10|Laptop:5|full,10")
あなたのタスクは以下の通りです:
- 以前のレッスンと同じ、
Price(float64) とQuantity(int) フィールドを持つProduct構造体を使用します - 最初の入力をパースし、既存の商品データで在庫マップを初期化します
- システムの起動メッセージを表示します:
"=== INVENTORY MANAGEMENT SYSTEM ===""System initialized with [number_of_products] products""Starting interactive session..."
- 2番目の入力をパースして、実行する操作のシーケンスを取得します
- 3番目の入力をパースして、各操作のパラメータを取得します
- シーケンス内の各操作について、操作ヘッダーを表示し、対応するアクションを実行します:
"check"の場合:"--- STOCK CHECK ---"を表示し、指定された商品の在庫を確認します"add"の場合:"--- ADD ITEM ---"を表示し、指定された商品を追加します"update"の場合:"--- UPDATE STOCK ---"を表示し、指定された商品の在庫を更新します"report"の場合:"--- GENERATE REPORT ---"を表示し、指定されたレポートを生成します"exit"の場合:"--- SYSTEM EXIT ---"を表示し、終了情報を表示します
- 以前のレッスンと同様に、数量とエラーを返す
checkStock関数を実装します - 以前のレッスンと同様に、商品を追加してエラーを返す
addNewItem関数を実装します - 以前のレッスンと同様に、数量を更新してエラーを返す
updateStock関数を実装します - 以前のレッスンと同様に、レポートを作成する
generateReport関数を実装します "check"操作について:- パラメータを確認する商品名として使用します
- 表示:
"Checking stock for: [product_name]" - 見つかった場合:
"Stock level: [quantity] units" - 見つからない場合:
"Product not found in inventory"
"add"操作について:"product_name:price:quantity"形式のパラメータをパースします- 表示:
"Adding new product: [product_name]" - 成功した場合:
"Product added successfully" - 失敗した場合:
"Failed to add product: [error_message]"
"update"操作について:"product_name:change"形式のパラメータをパースします- 表示:
"Updating stock for: [product_name]" - 成功し、変化量が正の場合:
"Added [change] units. New stock: [new_quantity]" - 成功し、変化量が負の場合:
"Removed [absolute_change] units. New stock: [new_quantity]" - 失敗した場合:
"Update failed: [error_message]"
"report"操作について:"report_type,threshold"形式のパラメータをパースします- 表示:
"Generating [report_type] report with threshold [threshold]" - 以前のレッスンと同様に、完全なレポートを生成して表示します
"exit"操作について:- 最終的な在庫統計を表示します:
"Final inventory status:""Total products: [total_products]""Total items: [total_items]""Total value: $[total_value]"
- 表示:
"Session completed successfully" - 表示:
"Thank you for using the Inventory Management System"
- 最終的な在庫統計を表示します:
- 各操作(exitを除く)の後、次を表示します:
"Operation completed. Continuing to next operation..."
入力文字列の分割には strings パッケージ、文字列から数値への変換には strconv パッケージ、エラー処理には errors パッケージ、フォーマットされた出力には fmt パッケージ、アルファベット順のソートには sort パッケージを使用してください。すべての価格と値は小数点以下2桁までフォーマットしてください。このチャレンジでは、複数の機能コンポーネントを統合し、適切なエラー処理と状態管理を備えた、まとまりのあるユーザー体験を提供する完全な対話型システムを作成する方法を学びます。
自分で試してみよう
package main
import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
)
type Task struct {
Name string
Completed bool
}
func removeTask(tasks []Task, index int) []Task {
return append(tasks[:index], tasks[index+1:]...)
}
func main() {
// Read input using bufio.Scanner to handle spaces properly
scanner := bufio.NewScanner(os.Stdin)
scanner.Scan()
_ = scanner.Text() // Read but don't use the number of tasks
scanner.Scan()
taskData := scanner.Text()
scanner.Scan()
indexStr := scanner.Text()
// Parse task data
taskEntries := strings.Split(taskData, ",")
var tasks []Task
for _, entry := range taskEntries {
parts := strings.Split(entry, ":")
if len(parts) >= 2 {
name := parts[0]
status := parts[1] == "true"
tasks = append(tasks, Task{Name: name, Completed: status})
}
}
// Convert index string to integer
index, _ := strconv.Atoi(indexStr)
// Store the name of the task to be removed
removedTaskName := tasks[index].Name
// Remove the task
tasks = removeTask(tasks, index)
// Display remaining tasks
completedCount := 0
for _, task := range tasks {
if task.Completed {
fmt.Printf("[x] %s\n", task.Name)
completedCount++
} else {
fmt.Printf("[ ] %s\n", task.Name)
}
}
// Print confirmation message
fmt.Printf("Task '%s' removed successfully!\n", removedTaskName)
// Print summary
totalCount := len(tasks)
incompleteCount := totalCount - completedCount
fmt.Printf("Total: %d tasks (%d completed, %d remaining)\n", totalCount, completedCount, incompleteCount)
}