【发布时间】:2018-08-21 16:25:03
【问题描述】:
我正在尝试创建一个将在表格中显示和排序的二维矩阵。
我在用数字填充矩阵/数组时遇到问题。我不想在那里重复,所以创建了一个临时的List。
我尝试了不同的方法来修复将num 添加到列表时遇到的索引越界异常,但我不知道发生了什么。
我最初将所有变量都设置为static,并且在方法中不需要。然后我尝试将它们放入方法中,看看如果变量不是 static 会发生什么。
我将如何解决此错误? (全部在控制台应用程序中完成)
static int max;
static int max_row;
static int max_col;
//static int[,] matrixArray = new int[max_row, max_col];
//static List<int> list = new List<int>();
//Filling the matrix
public static void matrixFill(int[,] matrixArray, List<int> list)
{
for (int x = 0; x < max_row; x++)
{
for (int y = 0; y < max_col; y++)
{
Random rand = new Random();
int num = rand.Next(10, 100);
if (!list.Contains(num))
{
matrixArray[x, y] = num;
//Index error occurs here
list.Add(num);
}
else
{
y--;
}
}
}
}
//What is happening in the main method until the error
int[,] matrixArray = new int[max_row, max_col];
List<int> list = new List<int>();
Console.Write("Please enter matrix size: ");
Int32.TryParse(Console.ReadLine(), out max);
max_row = max;
max_col = max;
Console.WriteLine();
matrixFill(matrixArray, list);
【问题讨论】:
-
使用 getupperbound 和你的数组索引进行循环