对于if(array [i + 1])超出数组边界的循环;如何循环开始?

时间:2013-12-04 00:28:46

标签: c# arrays for-loop indexoutofboundsexception

我有一个数组和for循环if语句,用于检查i + 1。但是,在循环的最后一次迭代中,数组超出范围。当发生这种情况时,我想循环回到数组的开头。回到array[0]的最佳方法是什么?这是我的代码:

int[] array = new int[5];
array[0] = new int(5);
array[1] = new int(7);
array[2] = new int(3);
array[3] = new int(1);
array[4] = new int(9);

for (int i = 0; i < array.Length; i++)
{
    if (array[i + 1] != 0)
        // Do something (obviously in this example, this will always occur)
    {
}

我可以执行以下操作,但它需要我复制我的代码(我当前的代码很大)。有没有更好的方法来做到以下几点?

int[] array = new int[5];
array[0] = new int(5);
array[1] = new int(7);
array[2] = new int(3);
array[3] = new int(1);
array[4] = new int(9);

for (int i = 0; i < array.Length; i++)
{
    if (i != array.Length - 1)
    {
        if (array[i + 1] != 0)
            // Do something (obviously in this example, this will always occur)
        {
    }
    else
    {
        if (array[0] != 0)
            // Do something (obviously in this example, this will always occur)
        {
    }
}

3 个答案:

答案 0 :(得分:6)

使用模数:

if(array[(i+1) % array.Length] != 0) {...}

这将基本上从(i + 1)减去array.Length直到(i + 1)&lt; array.Length

答案 1 :(得分:1)

for (int i = 0; i < array.Length; i++)
{
    if ((i + 1 < array.Length && array[i + 1] != 0) || (i + 1 == array.Length && array[0] != 0))
        // Do something (obviously in this example, this will always occur)
    {
}

答案 2 :(得分:0)

array[(i + 1) % array.Length]

应该在没有太多痛苦的情况下做到这一点。