回顾:管理仓库
本课属于 Coddy C# 学习旅程的“逻辑与流程”单元。第 54 课,共 66 课。
挑战
中等使用字典创建一个仓库库存管理系统。你的任务是实现 ManageWarehouse 方法,执行以下操作:
- 首先,按以下格式打印所有物品及其数量:"Item: [item], Quantity: [quantity]"
- 检查库存中是否有 "apples",并打印:"Apples in stock: [True/False]"
- 如果存在 "bananas",就将其数量增加 10(直接修改值)
- 移除数量为 0 的物品
- 打印仓库中不同物品的总数
- 最后,返回更新后的库存字典
亲手试试
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
class Program
{
public static Dictionary<string, int> ManageWarehouse(Dictionary<string, int> inventory)
{
// 在这里编写你的代码
return inventory;
}
static void Main(string[] args)
{
Dictionary<string, int> inventory = new Dictionary<string, int>();
// 读取第一行,检查是否为 JSON 格式
string firstLine = Console.ReadLine();
// 检查输入是否为 JSON 格式
if (firstLine != null && firstLine.StartsWith("{") && firstLine.EndsWith("}"))
{
try
{
// 处理 JSON 输入
string jsonContent = firstLine.Substring(1, firstLine.Length - 2);
// 按引号外的逗号拆分
string pattern = @",(?=(?:[^""]*""[^""]*"")*[^""]*$)";
string[] entries = Regex.Split(jsonContent, pattern);
foreach (string entry in entries)
{
// 使用正则表达式提取键和值
Match match = Regex.Match(entry, @"""([^""]+)""\s*:\s*(\d+)");
if (match.Success)
{
string keyMatch = match.Groups[1].Value;
int valueMatch = int.Parse(match.Groups[2].Value);
inventory.Add(keyMatch, valueMatch);
}
}
}
catch (Exception ex)
{
Console.WriteLine($"Error parsing JSON input: {ex.Message}");
return;
}
}
else
{
// Process traditional input format
int n = int.Parse(firstLine);
for (int i = 0; i < n; i++)
{
string[] parts = Console.ReadLine().Split(':');
inventory.Add(parts[0], int.Parse(parts[1]));
}
}
Dictionary<string, int> result = ManageWarehouse(inventory);
// Print updated inventory
Console.WriteLine("Updated Inventory:");
foreach (var item in result)
{
Console.WriteLine($"{item.Key}: {item.Value}");
}
}
}逻辑与流程中的所有课
自己练习: C# 在线编译器