开发者

c# index outside the bounds of the array, never breaks out of the for-loop

My program compiles but when runnng it never breaks out of the loop and says the array is too big. This is my code:

public class ComparableArray
{   
    public stat开发者_如何学运维ic void Main()
    {
    taxpayer[] taxArray = new taxpayer[5];
    int x;
    for(x= 0; x < taxArray.Length; ++x)
        taxArray[x] = new taxpayer();

        Console.Write("Enter Social Security Number for taxpayer {0}: ", x+1);
        taxArray[x].SSN = Console.ReadLine();
                    Console.Write("Enter gross income for taxpayer {0}: ", x+1);
                    taxArray[x].Income = Convert.ToDouble(Console.ReadLine());
        taxpayer.getRates();
        x++;

    }
}

I'm not sure what I'm doing wrong, I would appreciate any help.


You are incrementing x twice in your loop:

Once here:

for(x= 0; x < taxArray.Length; ++x)

and once here:

x++;


You don't need to increment the loop counter x++; in the body of the loop. The loop already does that.


The for loop should be declared a bit differently:

// notice the inclusion of the variable type in the for
// and you want to use x++, not ++x
for(int x= 0; x < taxArray.Length; x++)

But, the real problem is the incrementing of x++ inside the loop. Since the for loop declaration includes an incrementer (x++), there's no need to increment inside the loop as well.


All the answers were incorrect, thanks for the help though. I was using x twice; once in the for loop and also in the Console.Write, I just changed the for loop to y instead and works great.

int x=0;
int y;
for(y= 0; y < taxArray.Length; ++y){
    taxArray[x] = new taxpayer();

    Console.Write("Enter Social Security Number for taxpayer {0}: ", x+1);
    taxArray[x].SSN = Console.ReadLine();
    Console.Write("Enter gross income for taxpayer {0}: ", x+1);
    taxArray[x].Income = Convert.ToDouble(Console.ReadLine());
    taxpayer.getRates();
    x++;
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜