开发者

I am working with arrays and need to sort the array. This array keeps showing out of range exceptions

I have established an array and a large textbox which displays the array. Basically, you enter a name, 4 quarterly sales figures and it calculates the yearly total. I am now starting on the sort button. This would sort given columns numbers from most to least. I have gotten an if statement that looks like it should work for column five (the total column). I keep getting an out of range exception and am not sure why. Any ideas out there? I am sure this is a simple problem I am not seeing.

do {
    swapFlag = false;
    for (n=0; n < lastIndexUsed; n++)
    {
         if (quarters[n, sortCol] < quarters[n+1, sortCol])
         {
             //Column 5
             temp = quarters[n,5];
             quarters[n,5] = quarters[n +1, 3];
             quarters[n +1, 3] = temp;
             //swapflag
             swapFlag = true;
         }
    }
} while (swapFlag);

This shows how I get 0-5 for sortCol:

if (rbRegion.Checked)
    sortCol = 0;

if (rb1.Check开发者_运维百科ed)
    sortCol = 1;

if (rb2.Checked)
    sortCol = 2;

if (rb3.Checked)
    sortCol = 3;

if (rb4.Checked)
    sortCol = 4;

if (rbTotal.Checked)
    sortCol = 5;

Button Variables:

int n;
int temp;
int sortCol = 0;
string ntemp;
bool swapFlag;

Global Variables

int lastIndexUsed = -1;
int[,] quarters = new int[10, 5];
string[] Branch = new string[10];


quarters is defined as

int[,] quarters = new int[10, 5];

since arrays are zero based this gives you index 0...4 on the second dimension but you are trying to access index 5:

temp = quarters[n,5];


It seems to me, that you could have n = quaters.size - 1, and therefore n + 1 = quaters.size. So it gets out of array's bound.


I smell the problem is with these:

quarters[n+1, sortCol]
quarters[n+1, 3]

Make sure n+1 is a valid index. What if lastIndexUsed itself is the maximum valid index? Then n+1 would cause IndexOutOfRangeException.


I'd suggest to use more instances of List<int> quartersSortCol0 and use if (rbRegion.Checked) quartersSortCol0.Sort() and avoid ineffective constructions like your "while-for" above. While you can use overload of Sort method with custom comparison.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜