【问题标题】:C# Issues with if-statement and 2 arraysif 语句和 2 个数组的 C# 问题
【发布时间】:2020-03-10 07:10:35
【问题描述】:

代码一直运行到第二个 for 循环中的 if 语句。我试过改变很多东西——添加了第二个数组,这样它就不会与 if 语句冲突。对其进行了调试并更改了最后一个 if 的真实语句,但它从未真正通过第 23 行,它显示 System.IndexOutOfRangeException: Index was outside the bounds of the array。

            Console.WriteLine("Number of inputs: ");
            int numInput = int.Parse(Console.ReadLine());
            int[] arrayOfNumbers = new int[numInput];
            int[] arrayOfNumbersClone = new int[numInput];
            for (int inc = 0; inc < arrayOfNumbers.Length; inc++)
            {
                Console.Write("Enter {0} element: ", inc + 1);
                arrayOfNumbers[inc] = Int32.Parse(Console.ReadLine());
                arrayOfNumbersClone[inc] = arrayOfNumbers[inc];
            }
            for (int inc = 0, dec = numInput; inc2 < dec; inc2++, dec--)
            {
                if (arrayOfNumbers[inc] == arrayOfNumbersClone[dec])
                {
                    counter++;
                }
                else
                {
                }

            }
            if(counter<=0)Console.WriteLine("The array is not symmetric");
            else Console.WriteLine("The array is symmetric");

【问题讨论】:

  • 您知道,在第二个循环中,您初始化“inc”,但测试并增加“inc2”,在“if”中,您使用从未修改过的“inc”?
  • 你必须初始化dec = numInput - 1

标签: c# arrays for-loop if-statement indexoutofboundsexception


【解决方案1】:

我认为这是因为您在 for 循环条件中使用了 inc2,但从未真正为其分配任何值

把你的代码改成

for (int inc2 = 0, dec = numInput; inc2 < dec; inc2++, dec--)

【讨论】:

    【解决方案2】:

    错误表示您试图获取数组中不存在的索引。所以只需添加检查条件:

    int counter = 0;
    int lengthNumbers = arrayOfNumbers.Length;
    int lengthNumbersClone = arrayOfNumbersClone.Length;            
    for (int inc2 = 0, dec = numInput; maxInc < dec; inc2++, dec--)
    {
        if (inc2 < lengthNumbers
            && dec < lengthNumbersClone
            && arrayOfNumbers[inc2] == arrayOfNumbersClone[dec])
            {
               counter++;
            }
            else
            {                }
    
    }
    

    【讨论】:

      【解决方案3】:

      假设 numInput = 5。

      然后您将创建一个包含 5 个元素的数组。第 5 个元素的索引为 4,因为索引从 0 开始计数。

      在第二个循环中声明 dec = numInput; 因此,dec 现在也是 5。

      在您的 if 语句中,您请求 arrayOfNumbersClone[dec]。 由于 dec 为 5,因此您要求第 5 个索引上的元素。这是第 6 项,不存在。因此,您会得到“System.IndexOutOfRangeException”

      将您的第二个 for 循环更改为以下内容应该可以解决您的问题

      for (int inc = 0, dec = numInput - 1; inc < dec; inc++, dec--)
      

      (还要注意未定义的'inc2'改为'inc')

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-12-07
        • 2015-07-30
        • 1970-01-01
        • 1970-01-01
        • 2015-12-18
        • 1970-01-01
        相关资源
        最近更新 更多