[英]“Index Out of Bounds” error when using the Split method for an Array
我正在尝试拆分此数组中的数据,但它一直给我这个错误:
索引超出范围。
数组的大小为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();
}
我使用常量(例如“ Guy 19”)尝试了您的代码。 .Split()方法将基于空格分解输入字符串。 如果您没有在空格后面输入数字,那么scoreInfo [1]将为空,并且解析将失败。
尝试在.Split()之后添加一个断点,以确定scoreInfo是否正确拆分为大小为2的数组,其中[0]是播放器的名称,[1]是整数。 如果要输入“ FirstName LastName 20”之类的名称,则位置[1]上的信息将不是整数,并且解析也将失败。
你的for-loop有点令人费解,您是否要为一个由10名玩家组成的团队进行10次循环? 您可以将对话框置于while循环中,并在解析失败或用户键入诸如“ exit”之类的内容时中断。
注意事项。 您正在使用SIZE
来表示循环应进行的迭代次数。 它不是阵列的大小。 您的数组只会随着拆分而变大。 如果用空格分隔作为分隔符,则数组中将在索引0和1处有2个对象。
j
大于1时,您要写scoreInfo[j]
最后一部分将失败。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.