Click here to Skip to main content
15,884,298 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
so i made a 2d array and i want to add data into it but i always get this error
An unhandled exception of type 'System.IndexOutOfRangeException' occurred in kwaterminal.exe


this how i did it:

C#
int[,] terain = new int[x1, y1];
int placedmas = 0;
          while (placedmas < LandMasa)
          {
              Random rnd = new Random();
              int x = 0;
              int y = 0;
              x = rnd.Next(0,x1);
              y = rnd.Next(0,y1);

              terain[x1,y1] = 1; //here i get the error
          }


What I have tried:

searchin the error online but i could not find someone who was trying to do the same as me
Posted
Updated 21-Jan-18 0:07am
v2

1 solution

In this line:
C#
terain[x1,y1] = 1;
You probably meant [x, y] (the variables you just randomly generated). x1 and y1 are the dimensions you specified earlier, so the "bottom-right" element of this array will be at [x1 - 1, y1 - 1] which makes [x1, y1] out of range.

[Edit]

You'll also have to increase placedmas at some point, or you'll get stuck in an infinite loop.
 
Share this answer
 
v3
Comments
dolfijn3000 21-Jan-18 6:11am    
how do i fix this? i need a random location in my array to change into a 1. i tough this would wotk becous i declared x1 and y1 like this : int x1 = 16; int y1 = 25; : and i tought it would not go out of range becous i pick a random number from 0 to x1 and 0 to y1.
Thomas Daniels 21-Jan-18 6:12am    
I described in my answer how to fix it: "You probably meant [x, y]"

So, replace [x1,y1] by [x,y].
Thomas Daniels 21-Jan-18 6:12am    
Also, you probably have to increase placedmas at some point or it will always be below LandMasa.
dolfijn3000 21-Jan-18 6:14am    
well i now see why it was so broken. thx for helping me

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900