【问题标题】:Why is it showing Index is outside of the bounds of the array为什么它显示索引超出了数组的范围
【发布时间】:2016-10-21 01:01:59
【问题描述】:

我在第 33 行和第 46 行发现 index is out of bounds。这是为什么呢? 我正在尝试反转数组。我知道错误代码的含义,但我不知道为什么会得到它。 第 33 行 - 字符串反转 = ReverseArray(crafting); 第 46 行 - 返回 reverseCraft[5];

        //make an array to be reversed
        string[] craftArray = new string[5] { "Iron", "Stone", "Copper", "Steel", "Clay" };


        //create a variable to hold return value
        string[] crafting = new string[5];





        //function call the ReverseCraft method
        string reversed = ReverseArray(crafting);

        //Report the calculation to the user
        Console.Write("The array reversed is" + reversed);



    }
    public static string ReverseArray(string[] craft)
    {
        //create a variable and reverse
        string[] reverseCraft = new string[5] { craft[4], craft[3], craft[2], craft[1], craft[0] };
        //return value
        return reverseCraft[5];

    }
}
}

【问题讨论】:

  • reverseCraft[5] 应该是 [4]。因为数组是从零开始的。
  • 你的行数也超出范围
  • ReverseArray 方法应该返回一个字符串数组,而不是字符串。
  • 不回答你的问题,但将来我会首先使用 Array.Reverse()。如果您要编写一个函数来执行此类操作,我建议您使用带有边界检查的 for 循环..

标签: c# arrays indexing reverse


【解决方案1】:

您的反向方法的签名错误。它应该返回string[],像这样:

public static string[] ReverseArray(string[] craft) {
    //create a variable and reverse
    string[] reverseCraft = new string[5] { craft[4], craft[3], craft[2], craft[1], craft[0] };
    //return value
    return reverseCraft;
}

有了这段代码,您需要做的就是正确打印结果:

string[] reversed = ReverseArray(crafting);
//Report the calculation to the user
Console.Write("The array reversed is " + string.Join(", ", reversed));

【讨论】:

  • 好的,谢谢。除了使用 string.join 之外,还有其他方法吗?
  • @Xoax 可以,你可以写个循环。
【解决方案2】:

它在行上抛出一个错误

return reverseCraft[5];

因为没有 reverseCraft[5]。

reverseCraft的第一个元素是reverseCraft[0],最后一个元素是reverseCraft[4]。

【讨论】:

  • 修复了这部分。谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-05
  • 1970-01-01
相关资源
最近更新 更多