【发布时间】:2012-04-15 05:27:44
【问题描述】:
这段代码抛出异常,“索引超出了数组的范围”。这不应该简单地将每个拆分数据添加到指定的数组槽中吗?
while (input != null)
{
string[] splitInput = inputLine.Split();
EmpNum = int.Parse(splitInput[0]);
EmpName = (splitInput[1]);
EmpAdd = (splitInput[2]);
EmpWage = double.Parse(splitInput[3]);
EmpHours = double.Parse(splitInput[4]);
inputLine = (myFile.ReadLine());
Console.WriteLine("test {0},{1},{2}", EmpNum, EmpWage, EmpHours);
}
为了澄清一点,我正在从一个包含员工数据(姓名、地址、工作时间、员工编号、工资)的简单文本文件中读取数据。
为了清楚起见,我添加了整个主要方法。
using System;
using System.IO;
class Program
{
static void Main()
{
//declare an array of employees
Employee[] myEmployees = new Employee[10];
//declare other variables
string inputLine;
string EmpName;
int EmpNum;
double EmpWage;
double EmpHours;
string EmpAdd;
//declare filepath
string environment = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal) + "\\";
//get input
Console.Write("\nEnter a file name in My Documents: ");
string input = Console.ReadLine();
string path = environment + input;
Console.WriteLine("Opening the file...");
//read file
StreamReader myFile = new StreamReader(path);
inputLine = (myFile.ReadLine());
//split input
while (inputLine != null)
{
string[] splitInput = inputLine.Split();
EmpNum = int.Parse(splitInput[0]);
EmpName = (splitInput[1]);
EmpAdd = (splitInput[2]);
EmpWage = double.Parse(splitInput[3]);
EmpHours = double.Parse(splitInput[4]);
Console.WriteLine("test {0},{1},{2}", EmpNum, EmpWage, EmpHours);
}
Console.ReadLine();
}//End Main()
}//End class Program
【问题讨论】:
-
另外,如果需要任何其他信息,我可以发布更多我的代码。
-
当你拆分
inputLine时,你得到的元素少于 5 个 -
不应该是
while (input != null)而应该是while (inputLine != null)? -
另外,当抛出异常时,您可以查看堆栈跟踪并查看它发生的代码行 - 通常这会很快告诉您出了什么问题..