简体   繁体   中英

Error : Index out of bounds of array

 string[] lines = System.IO.File.ReadAllLines(@"C:\Users\myname\Desktop\test.txt");
        int cnt = lines.Count();

        int arraynum1 = 0;
        int arraynum2 = 1;
        int arraynum3 = 2;

        try
        {
            for (int x = 0; x < cnt; x++)
            {
                mc[0] = lines[arraynum1];
                mc[1] = lines[arraynum2];
                mc[2] = lines[arraynum3];

                arraynum1 = arraynum3 + 1;
                arraynum2 = arraynum3 + 1;
                arraynum3 = arraynum3 + 1;

                ListViewItem item = new ListViewItem(new[] { mc[0], mc[1], mc[2] });
                listView1.Items.Add(item);

            }

        }
        catch(Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }

Whenever I use my variable cnt in the for loop to specify which line to stop at, I receive the error listed in the title of this question, but whenever I set an integer in place of cnt in the loop it works flawlessly.

Shouldn't it be

    arraynum1 = arraynum1 + 1;
    arraynum2 = arraynum2 + 1;
    arraynum3 = arraynum3 + 1;

instead of

    arraynum1 = arraynum3 + 1;
    arraynum2 = arraynum3 + 1;
    arraynum3 = arraynum3 + 1;

Try this:

arraynum1 = arraynum1 + 1;
arraynum2 = arraynum2 + 1;
arraynum3 = arraynum3 + 1;

as you are currently referring to the same array arraynum3 in all the three cases.

arraynum1 = arraynum3 + 1;
arraynum2 = arraynum3 + 1;
arraynum3 = arraynum3 + 1;

Assuming your file contains 6 lines, this would be the values your mc[0]..mc[2] would hold inside your for loop:

Iteration 1 (x=0):

mc[0] = lines[0]
mc[1] = lines[1]
mc[2] = lines[2]

Iteration 2 (x=1):

mc[0] = lines[3]
mc[1] = lines[3]
mc[2] = lines[3]

Iteration 3 (x=2):

mc[0] = lines[4]
mc[1] = lines[4]
mc[2] = lines[4]

Iteration 4 (x=3):

mc[0] = lines[5]
mc[1] = lines[5]
mc[2] = lines[5]

Iteration 5 (x=4):

The exception you stated will be thrown here
mc[0] = lines[6]
mc[1] = lines[6]
mc[2] = lines[6]

Iteration 6 (x=5): Will never be reached

So instead of increasing your loop var x by 1 increase it by 3 like:

        for (int x = 0; x+2 < cnt ; x+=3)
        {
            mc[0] = lines[x];
            mc[1] = lines[x+1];
            mc[2] = lines[x+2];

            ListViewItem item = new ListViewItem(new[] { mc[0], mc[1], mc[2] });
            listView1.Items.Add(item);

        }

This approach will also consider the possibility that your file won't contain number of lines which isn't divideable by 3.

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