שילוב כל החלקים
חלק מהיחידה לוגיקה וזרימת התוכנית במסלול ה-GO של Coddy. שיעור 50 מתוך 68.
אתגר
קלהשלם את מערכת ניהול המלאי שלך על ידי יצירת תוכנית ראשית מקיפה שמשלבת את כל הפונקציונליות שבנית בשיעורים הקודמים. האתגר האחרון הזה מאגד אתחול מלאי, בדיקת מלאי, הוספת פריטים, עדכון מלאי והפקת דוחות לממשק שורת פקודה שלם עם ניווט מבוסס תפריטים.
תקבל שלוש קלטים:
- מחרוזת המכילה נתוני מלאי התחלתיים בפורמט
"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")
המשימה שלך היא:
- להשתמש באותו מבנה
Productמהשיעורים הקודמים, עם השדותPrice(float64) ו-Quantity(int) - לנתח את הקלט הראשון ולאתחל את מפת המלאי עם נתוני המוצרים הקיימים
- להציג את הודעת הפתיחה של המערכת:
"=== INVENTORY MANAGEMENT SYSTEM ===""System initialized with [number_of_products] products""Starting interactive session..."
- לנתח את הקלט השני כדי לקבל את רצף הפעולות שיש לבצע
- לנתח את הקלט השלישי כדי לקבל את הפרמטרים לכל פעולה
- עבור כל פעולה ברצף, להציג את כותרת הפעולה ולבצע את הפעולה המתאימה:
- עבור
"check": להציג את"--- STOCK CHECK ---"ולבדוק את המלאי של המוצר שצוין - עבור
"add": להציג את"--- ADD ITEM ---"ולהוסיף את המוצר שצוין - עבור
"update": להציג את"--- UPDATE STOCK ---"ולעדכן את המלאי של המוצר שצוין - עבור
"report": להציג את"--- GENERATE REPORT ---"ולהפיק את הדוח שצוין - עבור
"exit": להציג את"--- SYSTEM EXIT ---"ולהציג את פרטי היציאה
- עבור
- לממש את הפונקציה
checkStock, שמחזירה כמות ושגיאה כמו בשיעורים הקודמים - לממש את הפונקציה
addNewItem, שמוסיפה מוצרים ומחזירה שגיאה כמו בשיעורים הקודמים - לממש את הפונקציה
updateStock, שמעדכנת כמויות ומחזירה שגיאה כמו בשיעורים הקודמים - לממש את הפונקציה
generateReport, שמדפיסה את הדוח המתואר להלן עבור הפעולה"report" - עבור הפעולה
"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]", כאשר השגיאה היא"product already exists"
- לנתח את הפרמטר בפורמט
- עבור הפעולה
"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]", כאשר השגיאה היא"product not found", או"insufficient stock"כאשר הכמות החדשה תהיה קטנה מ-0
- לנתח את הפרמטר בפורמט
- עבור הפעולה
"report":- לנתח את הפרמטר בפורמט
"report_type,threshold", כאשר report_type הוא"low"או"full", ו-threshold הוא מספר שלם - להציג:
"Generating [report_type] report with threshold [threshold]" - לאחר מכן להדפיס את הדוח, כשהמוצרים מסודרים בסדר אלפביתי:
- עבור
"low":"=== LOW REPORT ===", לאחר מכן"Products with stock below [threshold]:", ולאחר מכן"- [name]: [quantity] units (Price: $[price])"עבור כל מוצר שכמותו נמוכה מהסף - עבור
"full":"=== FULL REPORT ===", לאחר מכן"Complete inventory (minimum threshold: [threshold]):", ולאחר מכן"- [name]: [quantity] units @ $[price] each [OK]"עבור כל מוצר, כאשר משתמשים ב-[LOW STOCK]במקום ב-[OK]אם הכמות נמוכה מהסף
- עבור
- לנתח את הפרמטר בפורמט
- עבור הפעולה
"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 (
"fmt"
"sort"
"strconv"
"strings"
)
type Product struct {
Price float64
Quantity int
}
func generateReport(inventory map[string]Product, reportType string, threshold float64) {
// Display report header
switch reportType {
case "full":
fmt.Println("=== FULL INVENTORY REPORT ===")
case "low_stock":
fmt.Println("=== LOW STOCK REPORT ===")
case "high_value":
fmt.Println("=== HIGH VALUE REPORT ===")
}
// Calculate general statistics
totalProducts := len(inventory)
totalItems := 0
totalValue := 0.0
for _, product := range inventory {
totalItems += product.Quantity
totalValue += product.Price * float64(product.Quantity)
}
averagePrice := totalValue / float64(totalItems)
// Display general 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)
fmt.Printf("Average Product Price: $%.2f\n", averagePrice)
// Filter products based on report type
var filteredProducts []string
for name, product := range inventory {
switch reportType {
case "full":
filteredProducts = append(filteredProducts, name)
case "low_stock":
if product.Quantity <= int(threshold) {
filteredProducts = append(filteredProducts, name)
}
case "high_value":
productValue := product.Price * float64(product.Quantity)
if productValue >= threshold {
filteredProducts = append(filteredProducts, name)
}
}
}
// Sort filtered products alphabetically
sort.Strings(filteredProducts)
// Display filtered products section header
switch reportType {
case "full":
fmt.Println("All Products:")
case "low_stock":
fmt.Printf("Products with stock ≤ %.0f:\n", threshold)
case "high_value":
fmt.Printf("Products with value ≥ $%.2f:\n", threshold)
}
// Display filtered products
filteredItems := 0
filteredValue := 0.0
for _, name := range filteredProducts {
product := inventory[name]
productValue := product.Price * float64(product.Quantity)
fmt.Printf("- %s: $%.2f × %d = $%.2f\n", name, product.Price, product.Quantity, productValue)
filteredItems += product.Quantity
filteredValue += productValue
}
// Display filtered statistics
fmt.Println("Filtered Results:")
fmt.Printf("Products shown: %d\n", len(filteredProducts))
fmt.Printf("Items in filtered products: %d\n", filteredItems)
fmt.Printf("Value of filtered products: $%.2f\n", filteredValue)
// Find most and least expensive products
var mostExpensiveName, leastExpensiveName string
var mostExpensivePrice, leastExpensivePrice float64
first := true
var sortedNames []string
for name := range inventory {
sortedNames = append(sortedNames, name)
}
sort.Strings(sortedNames)
for _, name := range sortedNames {
product := inventory[name]
if first {
mostExpensiveName = name
mostExpensivePrice = product.Price
leastExpensiveName = name
leastExpensivePrice = product.Price
first = false
} else {
if product.Price > mostExpensivePrice {
mostExpensiveName = name
mostExpensivePrice = product.Price
}
if product.Price < leastExpensivePrice {
leastExpensiveName = name
leastExpensivePrice = product.Price
}
}
}
fmt.Println("Price Analysis:")
fmt.Printf("Most expensive: %s at $%.2f\n", mostExpensiveName, mostExpensivePrice)
fmt.Printf("Least expensive: %s at $%.2f\n", leastExpensiveName, leastExpensivePrice)
// Find highest and lowest stock products
var highestStockName, lowestStockName string
var highestStock, lowestStock int
first = true
for _, name := range sortedNames {
product := inventory[name]
if first {
highestStockName = name
highestStock = product.Quantity
lowestStockName = name
lowestStock = product.Quantity
first = false
} else {
if product.Quantity > highestStock {
highestStockName = name
highestStock = product.Quantity
}
if product.Quantity < lowestStock {
lowestStockName = name
lowestStock = product.Quantity
}
}
}
fmt.Println("Stock Analysis:")
fmt.Printf("Highest stock: %s with %d units\n", highestStockName, highestStock)
fmt.Printf("Lowest stock: %s with %d units\n", lowestStockName, lowestStock)
// Inventory health assessment
lowStockCount := 0
highStockCount := 0
highValueCount := 0
for _, product := range inventory {
if product.Quantity <= 5 {
lowStockCount++
}
if product.Quantity > 20 {
highStockCount++
}
productValue := product.Price * float64(product.Quantity)
if productValue >= 500.0 {
highValueCount++
}
}
fmt.Printf("Low stock items (≤5): %d\n", lowStockCount)
fmt.Printf("High stock items (>20): %d\n", highStockCount)
fmt.Printf("High value items (≥$500): %d\n", highValueCount)
// Report completion
fmt.Println("Report generated successfully")
fmt.Printf("Threshold applied: %.2f\n", threshold)
}
func main() {
var inventoryData string
var reportConfig string
fmt.Scanln(&inventoryData)
fmt.Scanln(&reportConfig)
// Parse inventory data
inventory := make(map[string]Product)
if inventoryData != "" {
products := strings.Split(inventoryData, ",")
for _, productStr := range products {
parts := strings.Split(productStr, ":")
name := parts[0]
price, _ := strconv.ParseFloat(parts[1], 64)
quantity, _ := strconv.Atoi(parts[2])
inventory[name] = Product{Price: price, Quantity: quantity}
}
}
// Parse report configuration
configParts := strings.Split(reportConfig, ",")
reportType := configParts[0]
threshold, _ := strconv.ParseFloat(configParts[1], 64)
// Generate report
generateReport(inventory, reportType, threshold)
}כל השיעורים ביחידה לוגיקה וזרימת התוכנית
1בקרת זרימה מתקדמת
switch עם `fallthrough`יציאה מלולאות מקוננותהמשך לולאה מסוימתהצהרת `goto`סיכום – שליטה מתקדמת בלולאות4פרויקט: רשימת משימות פשוטה
הגדרת הפרויקטהוספת משימה2מבנים ושיטות
הגדרת שיטות במבניםמקבלי ערךמקבלי מצביעבחירת מקבליםשיטות לעומת פונקציותסיכום — התנהגות המבנים5מפות לעומק
מפות של Structsמצביעים כערכים במפהבדיקה אם מפות הן nilהשוואת מפותסיכום - מונה תדירות מילים8פרויקט: ניהול מלאי פשוט
סקירת הפרויקטבדיקת המלאיתרגלו בעצמכם: קומפיילר Go אונליין