C#新增“添加商品”和“删除商品”两个功能,程序建立好商品信息之后,在屏幕上显示“1 添加商品;2 删除商品”,根据输入1或者2,执行相应的功能
时间: 2023-10-08 11:05:52 浏览: 49
好的,我可以帮你解决这个问题。以下是实现此的 C# 代码示例:
```
using;
namespace ProductManagement
{
class Program
{
static void Main(string[] args)
{
// 商品列表
string[] products = new[0];
while (true)
{
显示菜单
Console.WriteLine("1 添加商品");
Console.WriteLine("2 删除商品");
// 获取用户输入
string input = Console.ReadLine();
if (input == "1")
{
// 添加商品
Console.WriteLine("请输入商品名称:");
string productName = Console.ReadLine();
// 扩展商品列表
Array.Resize(ref products, products.Length + 1);
products[products.Length - 1] = productName;
Console.WriteLine("商品添加成功!");
}
else if (input == "2")
{
// 删除商品
Console.WriteLine("请输入要删除的商品编号:");
for (int i = 0; i < products.Length; i++)
{
Console.WriteLine($"{i + 1} {products[i]}");
}
int index = int.Parse(Console.ReadLine()) - 1;
if (index >= 0 && index < products.Length)
{
// 缩小商品列表
for (int i = index; i < products.Length - 1; i++)
{
products[i] = products[i + 1];
}
Array.Resize(ref products, products.Length - 1);
Console.WriteLine("商品删除成功!");
}
else
{
Console.WriteLine("商品编号无效!");
}
}
else
{
Console.WriteLine("无效的操作!");
}
Console.WriteLine();
}
}
}
}
```
在上述代码中,我们使用了一个 `while` 循环来不断显示菜单和获取用户输入。如果用户输入了 `1`,则会提示用户输入商品名称,并将其添加到商品列表中;如果用户输入了 `2`,则会显示商品列表,并要求用户输入要删除的商品的编号,然后从商品列表中删除相应的商品。注意,在删除商品时,我们使用了 `Array.Resize` 方法来缩小商品列表。
希望这个代码示例可以帮助你解决问题。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)