Putting It All Together
Part of the Logic & Flow section of Coddy's GO journey — lesson 25 of 68.
Challenge
EasyComplete your inventory management system by creating a comprehensive main program that integrates all the functionality you've built in previous lessons. This final challenge brings together inventory initialization, stock checking, item addition, stock updates, and report generation into a complete command-line interface with menu-driven navigation.
You will receive three inputs:
- A string containing initial inventory data in the format
"product1:price1:quantity1,product2:price2:quantity2,product3:price3:quantity3"(e.g.,"Laptop:999.99:5,Mouse:25.50:15,Keyboard:75.00:8") - A string containing a sequence of menu operations in the format
"operation1,operation2,operation3"where operations can be"check","add","update","report", or"exit"(e.g.,"check,add,update,report,exit") - A string containing operation parameters in the format
"param1|param2|param3"where each parameter corresponds to the operation at the same position (e.g.,"Mouse|Monitor:299.99:10|Laptop:5|full,10")
Your task is to:
- Use the same
Productstruct from previous lessons withPrice(float64) andQuantity(int) fields - Parse the first input and initialize the inventory map with the existing product data
- Display the system startup message:
"=== INVENTORY MANAGEMENT SYSTEM ===""System initialized with [number_of_products] products""Starting interactive session..."
- Parse the second input to get the sequence of operations to perform
- Parse the third input to get the parameters for each operation
- For each operation in sequence, display the operation header and perform the corresponding action:
- For
"check": Display"--- STOCK CHECK ---"and check stock for the specified product - For
"add": Display"--- ADD ITEM ---"and add the specified product - For
"update": Display"--- UPDATE STOCK ---"and update stock for the specified product - For
"report": Display"--- GENERATE REPORT ---"and generate the specified report - For
"exit": Display"--- SYSTEM EXIT ---"and show exit information
- For
- Implement the
checkStockfunction that returns quantity and error as in previous lessons - Implement the
addNewItemfunction that adds products and returns error as in previous lessons - Implement the
updateStockfunction that updates quantities and returns error as in previous lessons - Implement the
generateReportfunction that creates reports as in previous lessons - For the
"check"operation:- Use the parameter as the product name to check
- Display:
"Checking stock for: [product_name]" - If found:
"Stock level: [quantity] units" - If not found:
"Product not found in inventory"
- For the
"add"operation:- Parse the parameter in format
"product_name:price:quantity" - Display:
"Adding new product: [product_name]" - If successful:
"Product added successfully" - If failed:
"Failed to add product: [error_message]"
- Parse the parameter in format
- For the
"update"operation:- Parse the parameter in format
"product_name:change" - Display:
"Updating stock for: [product_name]" - If successful and change is positive:
"Added [change] units. New stock: [new_quantity]" - If successful and change is negative:
"Removed [absolute_change] units. New stock: [new_quantity]" - If failed:
"Update failed: [error_message]"
- Parse the parameter in format
- For the
"report"operation:- Parse the parameter in format
"report_type,threshold" - Display:
"Generating [report_type] report with threshold [threshold]" - Generate and display the full report as in previous lessons
- Parse the parameter in format
- For the
"exit"operation:- Display final inventory statistics:
"Final inventory status:""Total products: [total_products]""Total items: [total_items]""Total value: $[total_value]"
- Display:
"Session completed successfully" - Display:
"Thank you for using the Inventory Management System"
- Display final inventory statistics:
- After each operation (except exit), display:
"Operation completed. Continuing to next operation..."
Use the strings package to split input strings, the strconv package to convert strings to numbers, the errors package for error handling, the fmt package for formatted output, and the sort package for alphabetical sorting. Format all prices and values to 2 decimal places. This challenge demonstrates how to create a complete interactive system that integrates multiple functional components into a cohesive user experience with proper error handling and state management.
Try it yourself
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)
}All lessons in Logic & Flow
1Advanced Control Flow
Switch with `fallthrough`Breaking from Nested LoopsContinuing a Specific LoopThe `goto` StatementRecap - Advanced Loop Control4Project: Simple Task List
Project SetupAdding a Task2Structs and Methods
Defining Methods on StructsValue ReceiversPointer ReceiversChoosing ReceiversMethods vs FunctionsRecap - Struct Behavior5Maps In-Depth
Maps of StructsPointers as Map ValuesTesting for Nil MapsComparing MapsRecap - Word Frequency Counter3Interfaces (The Basics)
What is an Interface?Defining an InterfaceImplementing an InterfaceUsing Interface TypesEmpty InterfaceType AssertionsType SwitchRecap - Shapes and Behaviors