【问题标题】:How to fill matrix in a class method?如何在类方法中填充矩阵?
【发布时间】:2015-08-12 09:44:06
【问题描述】:

我创建了一个类Matrix。我创建了一种填充矩阵的方法,但出现错误。有什么问题?

class Matrix
{
    private static int n, m;
    private string[,] arr = new string[n, m];
    public int N
    {
        set 
        {
            n = value;
        }
        get
        {
            return n;
        }
    }
    public int M
    {
        set
        {
            m = value;
        }
        get
        {
            return m;
        }
    }

    public string[,] SetMatrix()
    {
        for (int i = 0; i < n; i++)
        {
            for (int j = 0; j < m; j++)
            {
                arr[i, j] = Console.ReadLine();
            }
        }
        return arr;
    }
}


static void Main(string[] args)
{
    Matrix matrix = new Matrix();

    Console.WriteLine("- enter n");
    matrix.N = Convert.ToInt32(Console.ReadLine());
    Console.WriteLine("- enter m");
    matrix.M = Convert.ToInt32(Console.ReadLine());
    string[,] arr= new string[matrix.N, matrix.M];
    Console.WriteLine("enter matrix data");

    arr = matrix.SetMatrix(); //Error at this line

    Console.ReadKey();    
}

错误: An unhandled exception of type "System.IndexOutOfRangeException" in Matrix.exe

欲了解更多信息:Index was outside the bounds of the array.

提前致谢。

【问题讨论】:

  • 什么错误? ehat 是spreadSheet 变量吗?
  • 所以在方法SetTable 中抛出了错误,但是您向我们展示了方法SetMatrix。愿意展示真正的方法吗?还有什么错误?
  • SpreadsheetSimulator.exe 中“System.IndexOutOfRangeException”类型的未处理异常有关详细信息:索引超出了数组的范围。
  • @ВладимирНагорный,这应该是问题的一部分,而不是评论。你如何初始化你在SetMatrix中引用的arr
  • 尝试用i++j++替换++i ++j

标签: c# arrays class methods


【解决方案1】:

您没有在构造函数中设置您的 arr 数组。通过使用默认的 n 和 m 值,您的 arr 数组始终为 0 行和 0 列。这就是 indexOutOfRange 来的原因。

你可以通过使用这样的构造函数来解决这个问题-

public Matrix(int _n, int _m)
{
    n = _n;
    m = _m;
    arr = new string[n,m];
}

【讨论】:

  • 私有静态整数 n, m;私有字符串[,] arr = 新字符串[n, m];
  • 请发布完整的课程。看看你如何初始化你的私有 arr 数组会很有帮助。
猜你喜欢
  • 2021-07-19
  • 1970-01-01
  • 2011-08-07
  • 1970-01-01
  • 2017-02-22
  • 1970-01-01
  • 1970-01-01
  • 2013-06-07
  • 2015-08-12
相关资源
最近更新 更多