I have searched and looked for the answer but have not been able to get the answer that works.
To the question: I have created an array called backpack that can hold 5 items. I want the user to fill those 5 items. The project is supposed to be able to get back at a later time to fill in more (max 5).
This code are going to be implemented to another code that uses a menue and the user are going to be able to go from adding to the list and read the list. For example: The user goes to option 1 (to add) and adds shoes to the array. The user then goes back and in to option 2 to read whats in the list. Then the user goes back again and in to option 1 to add more items.
I have used a for loop but doesnt seems to work anyway, the error message i got is: System.IndexOutOfRangeException: 'Index was outside the bounds of the array.' Here is the code:
string[] backPack = new string[5];
string answer;
for (int i = backPack.Length; i <= 5; i++)
{
Console.Write("Vad vill du lägga till? "); // What do you want to add.
backPack[i] = Console.ReadLine();
Console.Write("Vill du lägga till fler produkter i din ryggsäck?(j/n): "); (Do you want to add more items to the backpack?
answer = Console.ReadLine().ToLower();
if (answer == "n")
{
break;
}
}
Note that it is in Swedish (the Write lines) but i have added a comment to translate this.
Can u please help me find whats the problem?
Edited code:
string[] backPack = new string[5];
string answer;
for (int i =0; i <= backPack.Length; i++)
{
Console.Write("Vad vill du lägga till? ");
backPack[i] = Console.ReadLine();
Console.Write("Vill du lägga till fler produkter i din ryggsäck?(j/n): ");
answer = Console.ReadLine().ToLower();
if (answer.Equals("n"))
{
break;
}
}
Now the earlier error does not happen directly but it seems the code wants to try and add a 6th item to the array. And then we get the same error again: System.IndexOutOfRangeException: 'Index was outside the bounds of the array.'
Please help.
try-catchblock to see what the error is. That should answer your question.for (int i =0; i <= backPack.Length; i++)when the answer provided clearly sayingfor (int i =0; i < backPack.Length; i++)<not<=this definitely will try to add sixth element to the array.