【问题标题】:2D Matrix index out of bounds二维矩阵索引超出范围
【发布时间】: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 和你的数组索引进行循环

标签: c# arrays matrix 2d


【解决方案1】:

问题是你在设置 max_row 和 max_col 参数之前定义了 matrixArray 的大小。

    List<int> list = new List<int>();

    Console.Write("Please enter matrix size: ");

    Int32.TryParse(Console.ReadLine(), out max);

    max_row = max;
    max_col = max;
    int[,] matrixArray = new int[max_row, max_col]; // move this here

相反,请将该定义移动到您询问用户最大尺寸之后,如上所述,以便您创建的矩阵与您期望的尺寸相同。

【讨论】:

  • 谢谢!难以置信,我尝试了这么多不同的东西,却错过了这么重要的细节。感谢您的帮助!
猜你喜欢
  • 2020-06-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-26
  • 2014-08-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多