【问题标题】:system.IndexOutOfRange exception in C# [duplicate]C#中的system.IndexOutOfRange异常[重复]
【发布时间】:2018-04-24 07:28:11
【问题描述】:

我知道以前有人问过这种问题,但我是菜鸟,无法理解数组在哪里越界。

PS 这不是每个 " system.IndexOutOfRange exception in C# " 的完全相同的副本,因为问题的情况和上下文完全不同。所以请先阅读问题在将其报告为“完全重复”之前。

 class Program
{
    static void Main(string[] args)
    {
        int highestcount = 0, e = 0, h = 0;
        string highest = "", a = "", b = "", j = "";
        int y = int.Parse(Console.ReadLine());
        e = y - 1;
        string[] savArray = new string[e];

        for (int count = 0; count < y; count++)
        {
            var x = Console.ReadLine().Split(' ');

            if (count+1 <= y)
            {
                j = x[count + 1];
                savArray[count] = j;
            }


        }

        for (int count1 = 0; count1 < y; count1++)
        {
            h = 0;
            a = savArray[count1];
            for (int count2 = 1; count2 < y; count2++)
            {
                b = savArray[ count2];
                if (a == b)
                {
                    h = h + 1;
                    if (highestcount <= h)
                    {
                        highestcount = h;
                        highest = a;
                    }
                }
            }

        }

        Console.Write(highest);
        Console.Read();
    }

}

该程序是寻找最常见的运动。 首先,用户必须输入列表中有多少个 no: 条目。

之后,用户必须输入他的姓名,然后输入他最喜欢的运动

如果您阅读该程序,我的意思是简单地将 x 的第二个值保存在数组中,因为每个第二个值都是用户给出的运动,因为我想保存运动的名称以检查哪个运动是更常见。

但例外是破坏了简单的想法,我坚持下去,请帮助。

【问题讨论】:

  • 你不能用调试器单步执行代码来看看发生了什么吗?
  • 他们可能不知道怎么做,docs.microsoft.com/en-us/visualstudio/debugger/… 可能会有所帮助!最终目标是逐步完成每次迭代的循环,并检查代码的变量/状态的值,以查看何时、为什么以及是什么导致索引超出范围。
  • 我已经做到了,但正如我所提到的,我是一个新手,无法发现问题出在哪里。
  • 你必须学习如何use a debugger。现在就这样做。
  • “问题的背景完全不同”——确切的背景并不重要。重要的是你有 Q&A 专门讨论的确切例外。坦率地说,没有人应该在 Stack Overflow 上询问有关修复IndexOutOfRangeException 的问题。这是一个简单的调试问题,标记的重复地址。

标签: c# arrays exception indexoutofboundsexception


【解决方案1】:

假设savArray 有 1 个元素。

然后你这样做:

 var x = Console.ReadLine().Split(' ');

 //Let's say x is "X" which is creates an array of size 1

 if (count + 1 <= y) <----this is true (0+1<=1)
 {  
      j = x[count + 1]; <----- BOOM x[1] when x has only one element.

【讨论】:

  • x 值的个数必须是“偶数”,因为用户正在输入他的姓名和运动的名称。
【解决方案2】:
for (int count = 0; count < y; count++)
    {
        var x = Console.ReadLine().Split(' ');

        if (count+1 <= y)
        {
            j = x[count + 1];
            savArray[count] = j;
        }


    }

没有仔细检查但是... [count + 1] 给定 for 循环约束 (count count + 1 当 count = y -1... 因此超出范围...我想。再次。没有仔细检查。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-01
    • 2012-03-29
    • 1970-01-01
    • 1970-01-01
    • 2011-04-27
    • 1970-01-01
    相关资源
    最近更新 更多