【问题标题】:2d array index out of range exception二维数组索引超出范围异常
【发布时间】:2016-06-21 15:35:23
【问题描述】:

只要我进入 while 循环,程序就会抛出 Index out of range 异常,而不会获取行和列的值。 getint 是一种在确保值在范围内的同时获取用户输入的方法

 while(filled>0)
        {
            row = getint("row:  ");
            row--;
            column = getint("column:  ");
            column--;
            fields[row, column]=getint("value:  ");
            filled--;
        }

编辑:

static int getint(string question)
    {
        string temp;
        int tempint=0;
        while (check != 0)
        {
            check = 0;
            Console.Write("\nPlease enter the {0}",question);
            temp = Console.ReadLine();
            if(!int.TryParse(temp, out tempint))
            {
                check++;
            }
            if(question.Length<14 & (tempint<1 | tempint>9))
            {
                check++;
                Console.WriteLine("Invalid Input");
            }
        }
        return tempint;
    }

【问题讨论】:

  • “不获取行和列值”是什么意思?我们不知道这些方法做了什么,也不知道fields 的大小是多少。请提供minimal reproducible example
  • 如果一进入while循环就抛出异常,那么问题可能出在getint(),但你没有包含该代码。
  • 需要更多代码。例如,这是否意味着从下到上阅读?
  • 您使用了错误的运算符。您应该使用&amp;&amp;|| 而不是&amp;|
  • 你在哪里实例化fields

标签: c# multidimensional-array


【解决方案1】:

如果代码越界只能发生在fields[row, column]中,您可以添加行列越界检查

row = Math.Max(row,0);
column= Math.Max(column,0);

row = Math.Min(fields.GetUpperBound(0), row);
column= Math.Min(fields.GetUpperBound(1), column);

【讨论】:

  • 只检查下限。与其说是支票,不如说是钳子。
  • 谢谢,我已经更新了我的答案以包括上限检查
【解决方案2】:

所以,错误出现在 while 循环中,我错过了这样一个事实,即我使用了全局变量“check”并且没有重置它的值,所以当它第一次退出循环时,它的值被设置为 0,因此出现了异常。

【讨论】:

    猜你喜欢
    • 2013-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-05
    • 2012-11-01
    • 1970-01-01
    相关资源
    最近更新 更多