检查库存
本课属于 Coddy GO 学习旅程的“逻辑与流程”单元。第 46 课,共 68 课。
挑战
简单为你的库存管理系统实现一个库存检查函数,安全地获取产品数量,并处理产品不存在的情况。本挑战基于上一课中的库存基础,并为库存查询添加错误处理。
你会收到两个输入:
- 一个包含现有库存数据的字符串,格式为
"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")
你的任务是:
- 使用上一课中的同一个
Product结构体,其中包含Price(float64)和Quantity(int)字段 - 通过逗号拆分第一个输入,获取各个产品条目
- 对于每个产品条目,通过冒号拆分,获取产品名称、价格和数量
- 将价格字符串转换为 float64,将数量字符串转换为 int
- 使用解析后的产品数据创建并填充
inventory映射 - 创建一个名为
checkStock的函数,该函数接收库存映射和产品名称作为参数,并返回 (int, error):- 如果产品存在于库存中,返回它的数量和 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")
}逻辑与流程中的所有课
自己练习: Go 在线编译器