Adrian Collado
Adrian Collado

Reputation: 709

C# IndexOutOfRangeException

At runtime the program says an index is out of range, but I don't know why.

The line that the error messager points out is

Points[counter + ((int)(radius * 100))].X = i;

If that one has an error, the next one (with the same index) must also have an error.

Points[counter + ((int)(radius * 100))].Y = (Points[counter].Y * -1);

Here is the code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication5
{
    class Program
    {
        static void Main(string[] args)
        {
            Circle circle = new Circle(new Point2D(30F, 30F), 10F);
            foreach (Point2D point in circle.Points)
            {
                Console.Write(point.X + " = X\n" + point.Y + " = Y");
                Console.ReadKey();
            }
        }
    }

    public struct Point2D
    {
        public float X;
        public float Y;

        public Point2D(float x, float y)
        {
            this.X = x;
            this.Y = y;
        }
    }

    class Circle
    {
        public Point2D[] Points;
        float h, k;
        float radiusStart, radiusEnd;
        int counter;

        public Circle(Point2D location, float radius)
        {
            Points = new Point2D[(int)(radius * 201)];
            h = location.X;
            k = location.Y;
            radiusStart = h - radius;
            radiusEnd = h + radius;

            for (float i = radiusStart; i <= radiusEnd; i++)
            {
                Points[counter].X = i;
                Points[counter].Y = (float)(Math.Sqrt((radius * radius) - ((i - h) * (i - h))) + k);
                Points[counter + ((int)(radius * 100))].X = i;
                Points[counter + ((int)(radius * 100))].Y = (Points[counter].Y * -1);
                counter++;
            }

            counter = 0;
        }
    }
}

Thank you in advance

Adrian Collado

Upvotes: 1

Views: 867

Answers (3)

Michael Davis
Michael Davis

Reputation: 251

The problem is in the increment step of your for loop: i = i++. It should just be i++ or ++i.

i++ increments i and returns its previous value, which you are then assigning back to i again. Therefore, i actually ends up with the same value in every iteration of the loop, so it is never greater than radiusEnd, and the loop never terminates (until counter exceeds the upper bound of the array and you get an out of range exception).

Upvotes: 3

dejuknow
dejuknow

Reputation: 1591

I've seen bizarre behavior with: i = i++

Try changing for (float i = radiusStart; i <= radiusEnd; i = i++) to just use i++ instead of i = i++.

Even if it doesn't fix your issue, it's much better form.

Upvotes: 2

Phil-R
Phil-R

Reputation: 2253

I noticed that "counter" is not initialized before you get in your loop, try initializing it to 0 before?

Upvotes: 2

Related Questions