c# - 如何在控制台中打印二维字符数组矩阵?
问题描述
我正在尝试创建一个像这样绘制矩形的方法:
--------------
| |
| ********** |
| ********** |
| ********** |
| ********** |
| ********** |
| ********** |
| ********** |
| ********** |
| |
--------------
我想在控制台中显示整个数组矩阵,但是当我尝试运行程序时,我得到了这个错误:
未处理的异常:System.IndexOutOfRangeException:索引超出了数组的范围。
我试图解决这个问题几个小时,但找不到问题。这是我的代码:
public static class Canvas
{
public static char[,] Draw (uint width, uint height)
{
char[,] page = new char[width + 4, height + 4];
for (uint i = 1; i < width + 3; ++i)
{
for (uint j = 1; j < height + 3; ++j)
{
page[i, j] = '1';
}
}
for (uint i = 0; i < width + 5; ++i)
{
page[0, i] = '-';
}
for (uint i = 0; i < width + 5; ++i)
{
page[height + 4, i] = '-';
}
for (uint j = 1; j < height + 4 ++j)
{
page[j, 0] = '|';
}
for (uint j = 1; j < height + 4; ++j)
{
page[j, width + 4] = '|';
}
return page;
}
}
解决方案
首先,我不知道这是否是一个错字,但你的第四个 FOR 循环缺少一个“;” 在第二个参数之后。
其次,++i和i++是有区别的。在 for 循环中,通常使用 i++,因为它首先使用值,然后加 1。如果使用 ++i,它会先加 1,然后使用值。这会将您的计数器 (i) 扔出数组边界。
之后,在某些循环中,您使用 Height +4 或 Width +4 在数组上写入,但这会导致一个位置超出数组,因为数组从 0 开始,并且您使用 Height +4 和 Width +4 on数组构造函数。
您的带有注释的代码:
public static class Canvas
{
public static char[,] Draw(uint width, uint height)
{
char[,] page = new char[width + 4, height + 4];
for (uint i = 1; i < width + 3; i++) //goes from 1 to 4 - 0 is null
{
for (uint j = 1; j < height + 3; j++) //goes from 1 to 4 - 5 is null
{
page[i, j] = '1';
}
}
for (uint i = 0; i < width + 5; i++) // goes from 0 to 6, but array ends at 5
{
page[0, i] = '-';
}
for (uint i = 0; i < width + 5; i++) // goes from 0 to 6, but array ends at 5
{
page[height + 4, i] = '-'; //the argument "height +4" throw the position out of the array, because arrays starts at 0
}
for (uint j = 1; j < height + 4; j++)
{
page[j, 0] = '|';
}
for (uint j = 1; j < height + 4; j++)
{
page[j, width + 4] = '|'; //the argument "width +4" throw the position out of the array, because arrays starts at 0
}
return page;
}
}
新代码:
public static class Canvas2
{
public static char[,] Draw(uint width, uint height)
{
char[,] page = new char[width + 4, height + 4];
for (uint i = 1; i < width + 3; i++)
{
for (uint j = 1; j < height + 3; j++)
{
page[i, j] = '1';
}
}
for (uint i = 0; i < width + 4; i++)
{
page[0, i] = '-';
}
for (uint i = 0; i < width + 4; i++)
{
page[height + 3, i] = '-';
}
for (uint j = 1; j < height + 4; j++)
{
page[j, 0] = '|';
}
for (uint j = 1; j < height + 4; j++)
{
page[j, width + 3] = '|';
}
return page;
}
}
输出:
推荐阅读
- c# - 关于继承的 ProtoBuf-Net 的问题?
- c++ - 如何避免 C++ 未定义行为欺骗 GoogleTest
- javascript - 如何使用 react js 和 asp.net core v3.0 下载文件
- c# - 多线程代码中的异步和等待问题
- php - CSS 和 Bootstrap 在 laravel5.8 中不起作用。我怎样才能解决这个问题?
- r - 无响应的滑块
- python - 由于 socket.py 中的错误,无法设置服务器
- c# - 如何解决 Azure Web 应用程序上的“请求标头过长”
- python - 尝试处理 IndentationError 异常
- kendo-ui-angular2 - 按下带有文本框值的回车键后如何触发事件?