简体   繁体   中英

C# Index out of bounds

I am trying to make a linear search where the user inputs a selection of numbers and then they input a random number and the program shows if it is in the list or not.

    int[] list = new int[10];
        bool found = false;
        for (int i = 0; i < 12;)
        {
            Console.WriteLine("Enter number to be stored.");
            list[i] =Convert.ToInt16(Console.ReadLine());
            i++;
        }
        Console.WriteLine("Enter number you want to find.");
        int n1 = Convert.ToInt16(Console.ReadLine());
        for (int i = 0; i <= 10;)
        {
            if (list[i] == n1)
            {
                Console.WriteLine(n1 + " is in the list.");
                found = true;
                Console.ReadKey();
            }
            else i++;

        }
        if (found == false)
        {
            Console.WriteLine("Element not in this list.");
        }
        Console.ReadKey();

I am pretty sure that the problem lies in this snippet of code.

    int[] list = new int[10];
    bool found = false;
    for (int i = 0; i < 12;)
    {
        Console.WriteLine("Enter number to be stored.");
        list[i] =Convert.ToInt16(Console.ReadLine());
        i++;
    }

An array beings with 0 so there are 11 element spaces right? So when i run it, i go past entering the 10th number and when i enter the 11th, it breaks and says

    System.IndexOutOfRangeException: 'Index was outside the bounds of the array.'

Firstly I'd recommend you read up on for loops and arrays in C#.

Secondly you don't want to hardcode the length in the for loop - let the framework do it for you using list.Length . You're seeing the crash because you're trying to assign a value to your array, but the index within your array doesn't exist.

int[] list = new int[10];
bool found = false;
for (int i = 0; i < list.Length; i++)
{
   // Do work with list[i]
}

When you say int[10]; you tell it to have 10 entries. They are counting from zero, yes, but that just means that your array has the indices 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 .

Your loop goes from i = 0 up to i = 11 before it stops because it's no longer smaller than twelve. But the index for the array can at most be 9 .

If you set a breakpoint, you should be able to look at the array contents in a debugger. This way, you could also test such things yourself.

It should be i < 10 or i <= 9 if your array only holds 10 objects. The 10 indices will be 0-9.

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