Menu
CoddyTech

Hepsini Bir Araya Getirme

Coddy'nin GO Journey'sinin Mantık ve Akış bölümünün bir parçası. Ders 50 / 68.

challenge icon

Görev

Kolay

Tüm envanter yönetimi sisteminizi, önceki derslerde geliştirdiğiniz tüm işlevleri bir araya getiren kapsamlı bir ana program oluşturarak tamamlayın. Bu son meydan okuma; envanter başlatma, stok kontrolü, ürün ekleme, stok güncelleme ve rapor oluşturma işlemlerini menü yönlendirmeli gezinmeye sahip eksiksiz bir komut satırı arayüzünde birleştiriyor.

Üç girdi alacaksınız:

  • "product1:price1:quantity1,product2:price2:quantity2,product3:price3:quantity3" biçiminde başlangıç envanteri verilerini içeren bir dize (ör. "Laptop:999.99:5,Mouse:25.50:15,Keyboard:75.00:8")
  • İşlemlerin "check", "add", "update", "report" veya "exit" olabildiği, "operation1,operation2,operation3" biçiminde bir menü işlemleri dizisi içeren bir dize (ör. "check,add,update,report,exit")
  • Her parametrenin aynı konumdaki işleme karşılık geldiği, "param1|param2|param3" biçiminde işlem parametrelerini içeren bir dize (ör. "Mouse|Monitor:299.99:10|Laptop:5|full,10")

Göreviniz:

  1. Önceki derslerdeki Product yapısını; Price (float64) ve Quantity (int) alanlarıyla birlikte kullanın
  2. İlk girdiyi ayrıştırın ve mevcut ürün verileriyle envanter haritasını başlatın
  3. Sistem başlangıç mesajını görüntüleyin:
    • "=== INVENTORY MANAGEMENT SYSTEM ==="
    • "System initialized with [number_of_products] products"
    • "Starting interactive session..."
  4. Gerçekleştirilecek işlemler dizisini almak için ikinci girdiyi ayrıştırın
  5. Her işlem için parametreleri almak üzere üçüncü girdiyi ayrıştırın
  6. Sıradaki her işlem için işlem başlığını görüntüleyin ve ilgili eylemi gerçekleştirin:
    • "check" için: "--- STOCK CHECK ---" ifadesini görüntüleyin ve belirtilen ürünün stokunu kontrol edin
    • "add" için: "--- ADD ITEM ---" ifadesini görüntüleyin ve belirtilen ürünü ekleyin
    • "update" için: "--- UPDATE STOCK ---" ifadesini görüntüleyin ve belirtilen ürünün stokunu güncelleyin
    • "report" için: "--- GENERATE REPORT ---" ifadesini görüntüleyin ve belirtilen raporu oluşturun
    • "exit" için: "--- SYSTEM EXIT ---" ifadesini görüntüleyin ve çıkış bilgilerini gösterin
  7. Önceki derslerdeki gibi miktar ve hata döndüren checkStock işlevini uygulayın
  8. Önceki derslerdeki gibi ürün ekleyen ve hata döndüren addNewItem işlevini uygulayın
  9. Önceki derslerdeki gibi miktarları güncelleyen ve hata döndüren updateStock işlevini uygulayın
  10. Aşağıdaki "report" işlemi için açıklanan raporu yazdıran generateReport işlevini uygulayın
  11. "check" işlemi için:
    • Parametreyi kontrol edilecek ürünün adı olarak kullanın
    • Şunu görüntüleyin: "Checking stock for: [product_name]"
    • Ürün bulunursa: "Stock level: [quantity] units"
    • Ürün bulunamazsa: "Product not found in inventory"
  12. "add" işlemi için:
    • Parametreyi "product_name:price:quantity" biçiminde ayrıştırın
    • Şunu görüntüleyin: "Adding new product: [product_name]"
    • Başarılıysa: "Product added successfully"
    • Başarısızsa: "Failed to add product: [error_message]"; burada hata "product already exists" olur
  13. "update" işlemi için:
    • Parametreyi "product_name:change" biçiminde ayrıştırın
    • Şunu görüntüleyin: "Updating stock for: [product_name]"
    • Başarılıysa ve değişiklik sıfır veya pozitifse: "Added [change] units. New stock: [new_quantity]"
    • Başarılıysa ve değişiklik negatifse: "Removed [absolute_change] units. New stock: [new_quantity]"
    • Başarısızsa: "Update failed: [error_message]"; hata "product not found" veya yeni miktar 0'ın altına düşecekse "insufficient stock" olur
  14. "report" işlemi için:
    • Parametreyi "report_type,threshold" biçiminde ayrıştırın; report_type "low" veya "full", threshold ise bir tam sayıdır
    • Şunu görüntüleyin: "Generating [report_type] report with threshold [threshold]"
    • Ardından, ürünleri alfabetik sırayla içeren raporu yazdırın:
      • "low" için: önce "=== LOW REPORT ===", ardından "Products with stock below [threshold]:", sonra miktarı eşik değerinin altında olan her ürün için "- [name]: [quantity] units (Price: $[price])"
      • "full" için: önce "=== FULL REPORT ===", ardından "Complete inventory (minimum threshold: [threshold]):", sonra her ürün için "- [name]: [quantity] units @ $[price] each [OK]"; miktar eşik değerinin altındaysa [OK] yerine [LOW STOCK] kullanın
  15. "exit" işlemi için:
    • Son envanter istatistiklerini görüntüleyin:
      • "Final inventory status:"
      • "Total products: [total_products]"
      • "Total items: [total_items]"
      • "Total value: $[total_value]"
    • Şunu görüntüleyin: "Session completed successfully"
    • Şunu görüntüleyin: "Thank you for using the Inventory Management System"
  16. Her işlemden sonra (exit hariç) şunu görüntüleyin: "Operation completed. Continuing to next operation..."

Girdi dizelerini bölmek için strings paketini, dizeleri sayılara dönüştürmek için strconv paketini, hata işleme için errors paketini, biçimlendirilmiş çıktı için fmt paketini ve alfabetik sıralama için sort paketini kullanın. Tüm fiyatları ve değerleri 2 ondalık basamakla biçimlendirin. Bu meydan okuma, uygun hata işleme ve durum yönetimiyle birden fazla işlevsel bileşeni tutarlı bir kullanıcı deneyiminde birleştiren eksiksiz, etkileşimli bir sistemin nasıl oluşturulacağını gösterir.

Kendin dene

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)
}

Mantık ve Akış bölümündeki tüm dersler

Kendi başına pratik yap: Online Go derleyicisi