简体   繁体   English

对数组使用拆分方法时出现“索引超出范围”错误

[英]“Index Out of Bounds” error when using the Split method for an Array

I am trying to split the data in this array, but it keeps giving me this error: 我正在尝试拆分此数组中的数据,但它一直给我这个错误:

index out of bounds. 索引超出范围。

The size of the array is 10. The line of code that is creating the error is 数组的大小为10。正在创建错误的代码行是

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

This is the code that I have: 这是我的代码:

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();
}

I tried your code using a constant, something like "Guy 19". 我使用常量(例如“ Guy 19”)尝试了您的代码。 The .Split() method will break up your input string based on spaces. .Split()方法将基于空格分解输入字符串。 If you're not entering a space followed by a number, then your scoreInfo[1] will be empty and parsing will fail. 如果您没有在空格后面输入数字,那么scoreInfo [1]将为空,并且解析将失败。

Try adding a break point after your .Split() to determine if scoreInfo is correctly split into a size 2 array, with [0] being the name of the player and [1] being an integer score. 尝试在.Split()之后添加一个断点,以确定scoreInfo是否正确拆分为大小为2的数组,其中[0]是播放器的名称,[1]是整数。 If you're entering a name like "FirstName LastName 20" then the information at position [1] is not going to be an integer and the parsing will also fail. 如果要输入“ FirstName LastName 20”之类的名称,则位置[1]上的信息将不是整数,并且解析也将失败。

Your for-loop is sort of puzzling, are you looping through 10 times for a team of 10 players? 你的for-loop有点令人费解,您是否要为一个由10名玩家组成的团队进行10次循环? You could put your dialog in a while loop and break out when parsing fails or the user types something like "exit". 您可以将对话框置于while循环中,并在解析失败或用户键入诸如“ exit”之类的内容时中断。

A few things of note. 注意事项。 You are using SIZE to denote how many iterations your loop should make. 您正在使用SIZE来表示循环应进行的迭代次数。 It is not the size of your array. 它不是阵列的大小。 Your array is only going to be large as the split makes it. 您的数组只会随着拆分而变大。 If you split with a space as the delimiter, you're going to have 2 objects in the array at indices 0 and 1. 如果用空格分隔作为分隔符,则数组中将在索引0和1处有2个对象。

That last section where you're saying to write scoreInfo[j] will fail as soon as j is larger than 1. j大于1时,您要写scoreInfo[j]最后一部分将失败。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM