我正在做一个方法,其中用户选择他/她想要列出的杂货项目的数量。食品杂货数量之前由intGroceryAmount (从strGroceryAmount解析)声明
现在,如果用户想要向杂货店列表添加另一个项目,则必须将数组大小增加1,并且必须显示杂货店列表中的所有项目,包括新添加的项目
我尝试将数组大小加1,以便现在有一个额外的空间,并将用户输入的空白空间分配给新的杂货商品。不幸的是,这就是错误发生的地方
附言:末尾显示的循环是“假定”显示食品杂货店中的所有商品。
strNumofPurchaseArray = new string[intGroceryAmount + 1];
System.Console.WriteLine("What is the new item you wish to enter?");
strNewItemInput = System.Console.ReadLine();
strNumofPurchaseArray[intGroceryAmount + 1] = strNewItemInput;
System.Console.WriteLine("\nYour new list of Grocery item is shown below:\n");
while (intNewItemCounter < intGroceryAmount)
{
System.Console.WriteLine("Grocery item #" + (intNewItemCounter + 1) + "is: " + strNumofPurchaseArray[intNewItemCounter]);
intNewItemCounter++;发布于 2014-04-03 07:43:58
数组从0开始。你在第四行写错了,应该是strNumofPurchaseArray[intGroceryAmount] = strNewItemInput;
您正在创建一个intGroceryAmount项的数组,但是数组中的最高索引是intGroceryAmount -1,最低索引是0。
发布于 2014-04-03 07:44:45
如果您希望能够调整列表的大小,那么我建议您使用List<string>,当您调用Add时,它将自动调整大小。如果您必须坚持使用数组,那么您可能应该查看用于调整大小的Array.Resize方法,该方法会自动将旧数组中的项复制到新数组中。然后,您应该使用foreach循环来枚举这些项。
发布于 2014-04-03 07:45:47
在C#中,数组不是这样工作的。当你预先知道结构的大小时,它们工作得最好。如果需要动态地添加和删除项,最好的选择是List<T>类
var strNumofPurchaseArray = new List<string>();
System.Console.WriteLine("What is the new item you wish to enter?");
strNewItemInput = System.Console.ReadLine();
strNumofPurchaseArray.Add(strNewItemInput);
System.Console.WriteLine("\nYour new list of Grocery item is shown below:\n");
for(int i=0; i< strNumofPurchaseArray.Count; i++)
{
System.Console.WriteLine("Grocery item #" + (i + 1) + "is: " + strNumofPurchaseArray[i]);
}https://stackoverflow.com/questions/22825155
复制相似问题