首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >索引超出了数组的界限:添加了杂货项目列表

索引超出了数组的界限:添加了杂货项目列表
EN

Stack Overflow用户
提问于 2014-04-03 07:38:28
回答 3查看 89关注 0票数 0

我正在做一个方法,其中用户选择他/她想要列出的杂货项目的数量。食品杂货数量之前由intGroceryAmount (从strGroceryAmount解析)声明

现在,如果用户想要向杂货店列表添加另一个项目,则必须将数组大小增加1,并且必须显示杂货店列表中的所有项目,包括新添加的项目

我尝试将数组大小加1,以便现在有一个额外的空间,并将用户输入的空白空间分配给新的杂货商品。不幸的是,这就是错误发生的地方

附言:末尾显示的循环是“假定”显示食品杂货店中的所有商品。

代码语言:javascript
复制
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++;
EN

回答 3

Stack Overflow用户

发布于 2014-04-03 07:43:58

数组从0开始。你在第四行写错了,应该是strNumofPurchaseArray[intGroceryAmount] = strNewItemInput;

您正在创建一个intGroceryAmount项的数组,但是数组中的最高索引是intGroceryAmount -1,最低索引是0。

票数 2
EN

Stack Overflow用户

发布于 2014-04-03 07:44:45

如果您希望能够调整列表的大小,那么我建议您使用List<string>,当您调用Add时,它将自动调整大小。如果您必须坚持使用数组,那么您可能应该查看用于调整大小的Array.Resize方法,该方法会自动将旧数组中的项复制到新数组中。然后,您应该使用foreach循环来枚举这些项。

票数 0
EN

Stack Overflow用户

发布于 2014-04-03 07:45:47

在C#中,数组不是这样工作的。当你预先知道结构的大小时,它们工作得最好。如果需要动态地添加和删除项,最好的选择是List<T>

代码语言:javascript
复制
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]);
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22825155

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档