Home > Blockchain >  Out of bounds error on iterating over array
Out of bounds error on iterating over array

Time:09-30

So This program has been giving me so much headaches, we're asked to use arrays where a list is more appropriate so this is not my choice.

After hours of work, I'm almost done. Then this happens.


Console.Clear();

Console.WriteLine("Would you like to search for an entry? Y/N."); // check if user wants to search.

Answer = Convert.ToString(Console.ReadLine());
Answer = Answer.ToUpper();
Console.Clear();

if (Answer == "Y")
{
    Console.WriteLine("Please enter the game you'd like to search for: "); // ask user for value
    search = Convert.ToString(Console.Read());

    for (i = 0; i <= 20; i  ) // run through array of names, checking if the entered value is present
 

        if (search.ToLower() == Name[i].ToLower() && i <20)
        {
            Console.WriteLine("Match Found!"); // Inform user there's a matching entry.
            Console.WriteLine(" ");
            Console.WriteLine("Game: "   Name[i]   ". Publisher: "   Publisher[i]   ". Genre: "   Genre[i]);

        }
        else
            Console.WriteLine("No match found! Check spelling."); // Inform user of no match.
}              
{
    Console.WriteLine("Clearing lines"); //start cleanup.
    Console.Clear();
    Console.WriteLine("End of program. Thank you for logging data. Press any key to exit");
    Console.ReadKey();
}

This is a segment of the code, the array referenced has an upper bound of 20.

CodePudding user response:

As you have 20 values in the array, your for loop condition should be i < 20.

In your case, it checks for 21 values, and since you have 20, it throws an exception, as there is no Name[20].

Here is how your code should look like:

if (Answer == "Y")
{
    Console.WriteLine("Please enter the game you'd like to search for: ");
    search = Convert.ToString(Console.Read());

    for (i = 0; i < 20; i  )
        if (search.ToLower() == Name[i].ToLower())
        {
            Console.WriteLine("Match Found!"); 
            Console.WriteLine(" ");
            Console.WriteLine("Game: "   Name[i]   ". Publisher: "   Publisher[i]   ". Genre: "   Genre[i]);

        }
        else
            Console.WriteLine("No match found! Check spelling."); 
}          

EDIT:

If you are not sure how many elements are present in the array and/or the array resizes during runtime, you can replace i < 20 with i < Name.Length.

CodePudding user response:

Well since we don't see original array we cannot be sure that it truly has 20 items. And we cannot be sure that over some time, the array won't get resized (maybe you will add some item into). What you want is to check the array size in each check of for loop like this:

for (i = 0; i < Name.Length; i  )

Also note that I've changed symbol from <= to < which was causing your out-of-bound exception. That is because you were iterating array of 20 items, indexed from 0.

array index -->  index started from 1
      0     -->       1.
      1     -->       2.
      2     -->       3.
             .
             .
     19     -->      20.  //this is the last item
     20     -->      21.  //out-of-bounds, will fail

CodePudding user response:

You are iterating the arrays 0 - 20. I am assuming your array size is 20 so it should iterate from 0-19.

 for (i = 0; i < 20; i  )

Or

 for (i = 0; i <= 19; i  )

CodePudding user response:

Arrays have zero based index, so you would want to change your for loop:

If your array is declared as string[] Name = new string[20]; this will index from 0-19

for (i = 0; i < 20; i  )

OR

for(i = 0; i < Name.Length; i  )

An element is a value in an Array. The length of an Array is the total number of elements it can contain. The lower bound of an Array is the index of its first element. An Array can have any lower bound, but it has a lower bound of zero by default. A different lower bound can be defined when creating an instance of the Array class using CreateInstance. A multidimensional Array can have different bounds for each dimension. An array can have a maximum of 32 dimensions.

system.array

  • Related