C# 多维字符数组上的IndexOutOfRangeException
代码在数组中循环,并将每个索引初始化为“*”。然而,我在C# 多维字符数组上的IndexOutOfRangeException,c#,arrays,for-loop,multidimensional-array,indexoutofrangeexception,C#,Arrays,For Loop,Multidimensional Array,Indexoutofrangeexception,代码在数组中循环,并将每个索引初始化为“*”。然而,我在Cave[I,j]上得到了一个IndexOutOfRangeException,我想要一些指导 char[,] Cave = new char[GridHeight, GridWidth]; for (int i = 0; i < GridWidth; i++) { for (int j = 0; j < GridHeight; j++) { Cave[i
Cave[I,j]
上得到了一个IndexOutOfRangeException
,我想要一些指导
char[,] Cave = new char[GridHeight, GridWidth];
for (int i = 0; i < GridWidth; i++)
{
for (int j = 0; j < GridHeight; j++)
{
Cave[i, j] = '*'; //Error Here
}
}
char[,]Cave=新字符[GridHeight,GridWidth];
对于(int i=0;i
- 为了澄清
,GridHeight
声明如下GridWidth
public const int GridHeight=5代码>
public const int GridWidth=7代码>
Cave[7,5]
,因为您的变量是向后的
char[,] Cave = new char[GridHeight, GridWidth]; // declare 5x7 array
for (int i = 0; i < GridWidth; i++) // range of i is 0 - 6
{
for (int j = 0; j < GridHeight; j++) // range of j is 0 - 4
{
Cave[i, j] = '*'; //Error Here // try to access Cave[6,4] - oops!
}
}
或者,如果对您更有意义,可以交换另一对:
char[,] Cave = new char[GridHeight, GridWidth];
for (int i = 0; i < GridHeight; i++)
{
for (int j = 0; j < GridWidth; j++)
{
Cave[i, j] = '*';
}
}
char[,]Cave=新字符[GridHeight,GridWidth];
对于(int i=0;i
通常我们看待事物的方式和编译器的方式不一样
以下是您的程序输出:
int GridHeight = 10;
int GridWidth = 5;
char[,] Cave = new char[GridHeight, GridWidth];
for (int i = 0; i < GridWidth; i++)
{
for (int j = 0; j < GridHeight; j++)
{
Console.Write(i+","+ j +" ");
// Cave[i, j] = '*'; //Error Here
}
Console.WriteLine();
}
如您所见,第一个变量是实际宽度,而不是高度。因此,要么重命名它们,要么交换它们:)
每当你考虑二维数组时(至少是控制台输出),请记住第一个轴是
X
(从左到右,升序),第二个轴是Y
(从上到下,升序)。你真的应该学会如何使用调试器,相信我,它会让你的生活更美好,按照惯例,在未来更容易,宽度通常是第一个维度,高度通常是第二个维度。应用这个规则,它应该是简单明了的。
int GridHeight = 10;
int GridWidth = 5;
char[,] Cave = new char[GridHeight, GridWidth];
for (int i = 0; i < GridWidth; i++)
{
for (int j = 0; j < GridHeight; j++)
{
Console.Write(i+","+ j +" ");
// Cave[i, j] = '*'; //Error Here
}
Console.WriteLine();
}
0,0 0,1 0,2 0,3 0,4 0,5 0,6 0,7 0,8 0,9
1,0 1,1 1,2 1,3 1,4 1,5 1,6 1,7 1,8 1,9
2,0 2,1 2,2 2,3 2,4 2,5 2,6 2,7 2,8 2,9
3,0 3,1 3,2 3,3 3,4 3,5 3,6 3,7 3,8 3,9
4,0 4,1 4,2 4,3 4,4 4,5 4,6 4,7 4,8 4,9