我已经访问过少于10行之前的索引后,索引超出范围[重复]

问题描述 投票:-2回答:1

我正在创建一个小文本地牢爬行器,地牢的每个楼层都是一个二维阵列的房间。出于某种原因,当你到达三楼,在创建阵列并确保所有房间都设置为null之后,当我到达floor3 [1,0]时我正在设置房间时它会抛出一个索引边界

使用断点并查看数组后,它显然有[1,0]以及[0,0]和[9,6]之间的所有其他内容。我运行一个for循环,访问该索引并将其设置为null并尝试更改for循环,而不是将所有房间更改为测试室,它没有问题。我检查了大概十几次,以确保没有任何错别字,或者我试图打错地板或任何简单的东西。我还写了一个简单的Console.Writeline(floor [1,0])测试行,以确保我不仅仅错过了一个拼写错误,我删除了那一行,它也发生在过去的那一点上。同样的方法适用于1楼和2楼。

floor3 = new RoomClass[9, 6];

//loop through everything and make sure that it's empty
for (int i = 0; i < 9; i++)
{
    for (int j = 0; j < 6; j++)
    {
        floor3[i, j] = null;
    }
}

//create rooms that actually need to exist.
floor3[0, 0] = new RoomClass("test1.", false, 0, 0);
floor3[0, 1] = new RoomClass("test2.", false, 0, 1);
floor3[0, 2] = new RoomClass("test5.", false, 0, 2);
floor3[0, 3] = new RoomClass("test3.", false, 0, 3);
floor3[0, 4] = new RoomClass("test4.", false, 0, 4);
floor3[0, 5] = new RoomClass("test5.", false, 0, 5);
floor3[0, 6] = new RoomClass("test5.", false, 0, 6);

floor3[1, 0] = new RoomClass("test6.", false, 1, 0);
floor3[1, 3] = new RoomClass("test7.", false, 1, 3);
floor3[1, 6] = new RoomClass("test8.", false, 1, 6);

floor3[2, 0] = new RoomClass("test9.", false, 2, 0);
(etc.)

这应该只是通过所有重要的索引,并为每个索引创建一个空间。

c# indexoutofboundsexception
1个回答
2
投票

floor3[0,6]超出阵列的范围。

floor3[1,6]一样,但它不会那么远。

请注意,您的循环条件可确保j小于6j的最高值是5

© www.soinside.com 2019 - 2024. All rights reserved.