此代码抛出异常,“索引超出了数组边界”。不应该这样简单地将每个分割数据添加到指定的数组插槽中吗?使用.Split()方法遇到问题
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
另外,如果需要任何其他信息,我可以发布更多的我的代码。 – xavi 2012-04-15 05:28:47
当你分割你的'inputLine'时,你得到少于5个元素 – bjarneh 2012-04-15 05:30:07
不应该'while(input!= null)'而不是'while(inputLine!= null)'? – 2012-04-15 05:30:43