【问题标题】:"Index Out of Bounds" error when using the Split method for an Array对数组使用拆分方法时出现“索引越界”错误
【发布时间】:2015-11-19 19:54:59
【问题描述】:

我正在尝试拆分此数组中的数据,但它一直给我这个错误:

索引超出范围。

数组的大小是 10。造成错误的代码行是

int score = int.Parse(scoreInfo[1]);

这是我的代码:

static void Main(string[] args)
{
    const int SIZE = 10;

    for (int j = 0; j < SIZE; j++)
    {
        // prompt the user
        Console.WriteLine("Enter player name and score on one line");
        Console.WriteLine("seperated by a space.");
        // Read one line of data from the file and save it in inputStr
        string inputStr = Console.ReadLine();
        // The split method creates an array of two strings
        string[] scoreInfo = inputStr.Split();
        // Parse each element of the array into the correct data type.
        string name = (scoreInfo[0]);
        int  score = int.Parse(scoreInfo[1]);
        if (inputStr == "")
        {
            Console.WriteLine(scoreInfo[j]);
        }
    }

    Console.ReadLine();
}

【问题讨论】:

  • 回答您的问题取决于输入的内容。请也添加输入。
  • 你的输入是什么?空白?短跑?逗号?在inputStr.Split(); 上设置一个断点,看看它返回了什么,显然它返回了一个数组,其中只有一个对象。
  • 显而易见的答案是 scoreInfo 实际上的长度是 1,而不是 10。
  • 您还应该将 if 语句直接移到 string inputStr = Console.ReadLine(); 之后,因为如果您已经在尝试解析而不先进行验证,这将没有好处。
  • @GlorinOakenfoot,事实证明 Split 没有任何参数会在所有空白字符上拆分。

标签: c# arrays split indexoutofboundsexception


【解决方案1】:

一些注意事项。您正在使用SIZE 来表示您的循环应该进行多少次迭代。它不是你的数组的大小。您的数组只会在拆分时变大。如果使用空格作为分隔符进行拆分,则数组中的索引 0 和 1 将有 2 个对象。

j 大于 1 时,您说要写入 scoreInfo[j] 的最后一部分将失败。

【讨论】:

  • 同意。基于 OP 给出的预期行为的假设,scoreInfo 应该在 for 循环之前初始化为 10 的大小,将 for 循环增加到 J+=2 然后有 string[] playerScore = inputStr.Split() 并设置 @ 987654329@。这样,在 for 循环结束时 scoreInfo 将是一个包含 10 个元素(5 个玩家姓名和 5 个分数)的数组
【解决方案2】:

我使用常量尝试了您的代码,例如“Guy 19”。 .Split() 方法将根据空格分解您的输入字符串。如果您没有输入空格后跟数字,那么您的 scoreInfo[1] 将为空并且解析将失败。

尝试在 .Split() 之后添加一个断点,以确定 scoreInfo 是否正确拆分为大小为 2 的数组,其中 [0] 是玩家的姓名, [1] 是整数分数。如果您输入的是“FirstName LastName 20”之类的名称,那么位置 [1] 处的信息将不是整数,解析也会失败。

您的 for 循环有点令人费解,您是否为一个 10 人的团队循环了 10 次?你可以把你的对话放在一个while循环中,当解析失败或者用户输入“exit”之类的东西时就会中断。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-06
    • 2015-03-22
    相关资源
    最近更新 更多