C#产品数组填充方法循环异常问题求助
问题分析与修复方案
核心问题1:死循环
你代码里的第二个while (productId != null)循环完全没有终止条件——循环内部既没修改productId的值,也没加break这类跳出逻辑。只要一开始输入的productId不是空,这个循环就会永远跑下去,重复让你输入产品信息,根本停不下来。
核心问题2:数据无法保存
你只读取了产品名称、类别这些字段的值,但完全没把它们存入传入的Product[] products数组里,等于读了白读,自然看不到保存的数据。
修复后的完整代码
private static void GetProductData(Product[] products) { Console.WriteLine("类别名称:Electronics, Books, Apparel, Toys, Others"); Console.WriteLine("类别编码:e-, b-, a-, t-, o-"); // 遍历数组,逐个填充产品数据 for (int i = 0; i < products.Length; i++) { Console.Write("请输入产品ID(格式:4位,首字符小写,第二位是-,后两位为数字):"); string productId = Console.ReadLine(); // 验证ID格式,直到输入正确 while (!CheckString(productId)) { Console.WriteLine("产品ID格式无效,请重新输入:"); productId = Console.ReadLine(); } Console.Write("请输入产品名称:"); string productName = Console.ReadLine(); Console.Write("请输入产品类别:"); string productCategory = Console.ReadLine(); // 处理数量输入,避免非数字导致崩溃 int productQuantity; Console.Write("请输入产品数量:"); while (!int.TryParse(Console.ReadLine(), out productQuantity)) { Console.WriteLine("数量必须是整数,请重新输入:"); } // 处理价格输入,同理避免崩溃 double productPrice; Console.Write("请输入产品价格:"); while (!double.TryParse(Console.ReadLine(), out productPrice)) { Console.WriteLine("价格必须是数字,请重新输入:"); } // 将输入的数据存入数组 products[i] = new Product { ProductId = productId, ProductName = productName, ProductCategory = productCategory, // 这里要和你的Product类字段名对应,比如Quantity/Price Quantity = productQuantity, Price = productPrice }; // 可选:如果还没填满数组,询问是否继续添加 if (i < products.Length - 1) { Console.WriteLine("是否继续添加产品?(输入y继续,其他键停止)"); string choice = Console.ReadLine()?.ToLower(); if (choice != "y") { break; } } } } // 确保CheckString方法正确验证ID格式 private static bool CheckString(string productId) { if (string.IsNullOrEmpty(productId) || productId.Length != 4) return false; return char.IsLower(productId[0]) && productId[1] == '-' && char.IsDigit(productId[2]) && char.IsDigit(productId[3]); }
关键修改点说明
- 用
for循环替代死循环:基于传入数组的长度控制填充次数,不会无限循环。 - 添加数据存储逻辑:把输入的字段值实例化成
Product对象,存入数组对应索引位置。 - 优化输入验证:用
int.TryParse和double.TryParse处理数量、价格输入,避免用户输错格式导致程序崩溃。 - 可选的终止逻辑:允许用户在填满数组前提前停止输入。
内容的提问来源于stack exchange,提问作者Don Boss
相关产品推荐
相关产品推荐

