Stok Kontrolü
Coddy'nin GO Journey'sinin Mantık ve Akış bölümünün bir parçası — ders 46 / 68.
Görev
KolayEnvanter yönetim sisteminiz için, ürün miktarlarını güvenli bir şekilde alan ve ürünlerin mevcut olmadığı durumları yöneten bir stok kontrol fonksiyonu uygulayın. Bu görev, önceki dersteki envanter temeli üzerine inşa edilmiştir ve stok sorguları için hata yönetimi ekler.
İki girdi alacaksınız:
"product1:price1:quantity1,product2:price2:quantity2,product3:price3:quantity3"formatında mevcut envanter verilerini içeren bir dize (örneğin,"Laptop:999.99:5,Mouse:25.50:15,Keyboard:75.00:8")"product1,product2,product3"formatında stok kontrol taleplerini içeren bir dize (örneğin,"Mouse,Tablet,Keyboard")
Göreviniz şunları yapmaktır:
- Önceki dersteki
Price(float64) veQuantity(int) alanlarına sahip aynıProductstruct'ını kullanın - Bireysel ürün girişlerini elde etmek için ilk girdiyi virgüllere göre ayırarak ayrıştırın
- Her ürün girişi için, ürün adını, fiyatını ve miktarını elde etmek üzere iki nokta üst üste işaretine göre ayırın
- Fiyat dizesini float64'e ve miktar dizesini int'e dönüştürün
- Ayrıştırılan ürün verileriyle
inventorymap'ini oluşturun ve doldurun - Parametre olarak inventory map'ini ve bir ürün adını alan ve (int, error) döndüren
checkStockadında bir fonksiyon oluşturun:- Ürün envanterde mevcutsa, miktarını ve nil döndürün
- Ürün mevcut değilse, 0 ve
"product not found: [product_name]"mesajını içeren bir hata döndürün
- Kontrol edilecek ürün listesini elde etmek için ikinci girdiyi virgüllere göre ayırarak ayrıştırın
- Stok kontrol başlığını görüntüleyin:
"Stock Check Results:" - Kontrol listesindeki her ürün için
checkStockfonksiyonunu çağırın ve sonuçları görüntüleyin:- Hata yoksa:
"[product_name]: [quantity] units in stock" - Hata varsa:
"[product_name]: Error - [error_message]"
- Hata yoksa:
- Özet istatistikleri sayın ve görüntüleyin:
"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]"
- Bulunan ürünler için toplam stoğu görüntüleyin:
"Total stock for found products: [sum_of_quantities_for_existing_products] units"
- Eksik ürünleri listeleyin:
- Eksik ürünler varsa:
"Missing products: [comma_separated_list_of_missing_products]" - Eksik ürün yoksa:
"All requested products are available"
- Eksik ürünler varsa:
Girdi dizelerini ayırmak için strings paketini, dizeleri sayılara dönüştürmek için strconv paketini, hata mesajları oluşturmak için errors paketini ve formatlı çıktı için fmt paketini kullanın. Bu görev, envanter yönetim sistemlerinde temel bir model olan uygun hata yönetimi ile güvenli veri alımının nasıl uygulanacağını gösterir.
Kendin dene
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")
}Mantık ve Akış bölümündeki tüm dersler
1İleri Seviye Kontrol Akışı
`fallthrough` ile Switchİç İçe Döngülerden ÇıkmaBelirli Bir Döngüye Devam Etme`goto` İfadesiÖzet - İleri Seviye Döngü Kontrolü4Proje: Basit Görev Listesi
Proje KurulumuGörev Ekleme2Structlar ve Metotlar
Structlarda Metot TanımlamaValue Receiver'larPointer Receiver'larReceiver SeçimiMetotlar ve FonksiyonlarÖzet - Struct Davranışı5Derinlemesine Map'ler
Struct Map'leriMap Değeri Olarak Pointer'larNil Map KontrolüMap'leri KarşılaştırmaÖzet - Kelime Frekansı Sayacı8Proje: Basit Envanter
Projeye Genel BakışStok Kontrolü3Arayüzler (Temeller)
Arayüz Nedir?Bir Arayüz TanımlamaBir Arayüzü UygulamaArayüz Tiplerini KullanmaBoş ArayüzTip OnaylamalarıTip SeçimiÖzet - Şekiller ve Davranışlar