此代碼拋出異常,「索引超出了數組邊界」。不應該這樣簡單地將每個分割數據添加到指定的數組插槽中嗎?使用.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