13,052,351 members (56,341 online)
Rate this:
See more:
i write a simple code but i have an strange exception .

```int[] vertex;
int[,] AMatrix;
int Length;

public void SetVertex()
{
Console.WriteLine("Please enter the number of vertices");
int n = Convert.ToInt32(Console.ReadLine());
while (n < 2)
{
Console.WriteLine("You must enter a number greater than 1\n plz enter another one:");
}
vertex = new int[n];
for (int i = 0; i <= n-1; i++)
vertex[i] = i;
}
public void SetEdges()
{
AdjacencyMatrix = new int[vertex.Length, vertex.Length];
for (int i = 0; i < vertex.Length; i++)
for (int j = 0; j < vertex.Length; j++)
AdjacencyMatrix[i, j] = 0;

Console.WriteLine("please enter the number of the edges:");
int e = Convert.ToInt32(Console.ReadLine());

for (int i = 0; i < e; i++)
{
Console.WriteLine("from ");
int s = 0;

Console.WriteLine("to ");
int d = 0;
AdjacencyMatrix[s, d] = 1; // <<-------- Exception happens here

}```

in line that i bold it i have an exception i cant understand, please help me to remove this exception :(
Posted 29-Jan-10 21:43pm
Updated 30-Jan-10 1:23am
v3

Rate this:

## Solution 1

The code seems to be fine,

Let me know what error you are getting.

Is it IndexOutOfRangeException?

If this is so, then you are setting a value to an array which is not allocated.

:)
Rate this:

## Solution 3

Since the exception happens at the line indicated, I would think that the user entered a digit that was out of range of the array. Since there are two values, and you didn't give us the values input by the user, it's impossible to say which is the bad one.

It is, however, the most probably cause. Christian mentioned that it could have been a non-numeric character entered by mistake, but that would have thrown an exception where you called `Convert.ToInt32`.

For what it's worth, your code is pretty bad. NEVER use one-character variable names for anything more important than a loop controller (even if this is just a homework assignment). I would also use a List of objects instead of an doubly-subscripted array of integers. Take the text-speak pout of your command prompts, and tell the user what the valid values are when prompting him for them. If you're going to learn how to write code, learn how to write it correctly. Finally, add some comments.
Rate this:

## Solution 2

I guess you don't really want help, or you'd have told us what the exception was.

elahe_eli wrote:

This will also throw an exception if a non number is entered.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Top Experts
Last 24hrsThis month
 OriginalGriff 313 David_Wimbley 100 Jochen Arndt 95 Richard MacCutchan 95 ppolymorphe 90
 OriginalGriff 5,536 RickZeeland 1,944 ppolymorphe 1,848 F-ES Sitecore 1,636 Dave Kreskowiak 1,409

Advertise | Privacy | Mobile
Web02 | 2.8.170713.1 | Last Updated 30 Jan 2010