简体   繁体   中英

Index was outside the bounds of the array: Grocery item list addition

I am doing a method where user chooses the amount of grocery items he/she wants to list. That grocery item amount was declared before by intGroceryAmount (parsed from strGroceryAmount)

Now if user wants to add another item to the grocery list, the array size has to be increased by 1, and all the items in the grocery list has to be shown, including the new addition

I tried to add 1 to the array size so that now there is an extra space, and assign that empty space the user input for the new grocery item. Unfortunately, this is where the error occurs

PS: The loop shown in the end is "supposed" to show all the items in the grocery

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++;

Arrays start at 0. You made a mistake on your 4th line, it should be strNumofPurchaseArray[intGroceryAmount] = strNewItemInput;

You're creating an array of intGroceryAmount items but the highest index in the array is intGroceryAmount - 1 and the lowest is 0.

If you want to be able to resize your list then I would suggest using a List<string> , which will resize automatically when you call Add . If you must stick with an array then you should probably look at the Array.Resize method for resizing, which will automatically copy the items from the old array into the new one as well. You should then use a foreach loop to enumerate the items.

Arrays don't work that way in C#. They work best when you know the size of the structure upfront. If you need to add and remove items dinamically, your best bet is the List<T> class

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]);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM