【发布时间】: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