2013-08-31 29 views
0

我想從文件讀取數據,拆分數據並保存到數組。代碼工作正常,除了拆分。它返回一個NullExceptionC#拆分不工作

任何幫助將不勝感激。

public static void LoadHandData(CurrentHand[] handData, string fileName) 
    { 
     string input = ""; //temporary variable to hold one line of data 
     string[] cardData; //temporary array to hold data split from input 

     StreamReader readHand = new StreamReader(fileName); 

     for (int counter = 0; counter < handData.Length; counter++) 
     { 

      input = readHand.ReadLine(); //one record 
      cardData = input.Split(' '); //split record into fields 

      int index = 0; 
      handData[counter].cardSuit = Convert.ToChar(cardData[index++]); 
      handData[counter].cardValue = Convert.ToInt16(cardData[index++]); 
     } 
     readHand.Close(); 
    } 
+3

*你在哪裏*得到例外?我懷疑你會發現基本上你的文件中沒有足夠的行。 'handData'有多大,文件有多長?如果ReadLine()返回數據的末尾,則返回null。 –

+0

你也許應該在Readline之後考慮一個守衛克勞斯,以確保它在分裂之前不爲空。 – Damon

+0

該文件只是一行即ie。 C 12 S 12 C 7 H 5 D 2.我試圖將char和int分割爲(手形數據)結構數組 –

回答

4

根據評論,你只有一行數據。但看看你的循環:

for (int counter = 0; counter < handData.Length; counter++) 
{ 
    input = readHand.ReadLine(); //one record 
    cardData = input.Split(' '); //split record into fields 

    int index = 0; 
    handData[counter].cardSuit = Convert.ToChar(cardData[index++]); 
    handData[counter].cardValue = Convert.ToInt16(cardData[index++]); 
} 

這是試圖讀取每手一行。在第二次迭代中,ReadLine將返回null,因此當您撥打input.Split()時,您將看到您看到的NullReferenceException

您需要閱讀一行並將其拆分。鑑於你只有一行文字,你可以使用File.ReadAllText來簡化:

string input = File.ReadAllText(fileName); 
string[] cardData = input.Split(' '); 

for (int counter = 0; counter < handData.Length; counter++) 
{ 
    handData[counter].cardSuit = Convert.ToChar(cardData[counter * 2]); 
    handData[counter].cardValue = Convert.ToInt16(cardData[counter * 2 + 1]); 
}