0

我正在尝试从文件中读取数据,拆分数据并保存到数组。除了拆分之外,代码工作正常。它正在返回一个NullException.

任何帮助将不胜感激。

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();
    }
4

1 回答 1

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将 return 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]);
}
于 2013-08-31T10:39:33.933 回答