读取文件记录并分配给数组

时间:2013-05-22 23:12:12

标签: c# arrays

我正在创建一个扑克统计WinForm程序,用于将玩家信息和8周的奖金以及总奖金金额写入文件并阅读该信息以显示在表单中。我在阅读每周8个奖金数量的文本框到我的阵列时遇到了问题。我收到“未设置为对象实例的对象引用”。错误。我在下面的代码中注意到我认为错误的来源。我已经包含了表单代码和我的类代码。我有什么想法我做错了吗?我希望我已经提供了足够的问题背景。在此先感谢!!

我的表单代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization;
using System.Text;
using System.Windows.Forms;

namespace PokerStats
{
    public partial class FormPokerStats : Form  // FormPokerStats inheriting from class Form
    {
        // declaring and assigning of variables needed for file read/write
        const char DELIM = ',';
        const string FILEPATH = @"C:\C# Project Output\";
        const string FILENAME = "PokerPlayers.txt";

        // declaring instances of Person, Location, and Winnings classes
        Person myplayer = new Person();
        Location mycasino = new Location();
        Winnings mywinnings = new Winnings();

        // constructing in/out FileStream/StreamReader/StreamWriter objects
        static FileStream inFile = new FileStream(FILEPATH + FILENAME, FileMode.OpenOrCreate, FileAccess.Read, FileShare.ReadWrite);
        StreamWriter writer = new StreamWriter(outFile);
        static FileStream outFile = new FileStream(FILEPATH + FILENAME, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
        StreamReader reader = new StreamReader(inFile);

        public FormPokerStats()
        {
            InitializeComponent();
        }

        // "Enter/Update Player" tab Enter Player button: read/assign user input, write to file, close file stream 
        private void buttonEnterPlayer_Click(object sender, EventArgs e)
        {
            // if directory does not exist, create it
            if (!(Directory.Exists(FILEPATH)))
            {
                // create directory
                Directory.CreateDirectory(FILEPATH);
            }

            try
            {
                // read user input and assign to variables; test for empty player inputs and reprompt for input, if necessary
                // Player Information fields
                // if any or all textboxes are left blank
                if ((textBoxSSN.Text == String.Empty || textBoxFirstName.Text == String.Empty || textBoxLastName.Text == String.Empty
                    || textBoxCasinoName.Text == String.Empty || textBoxCasinoState.Text == String.Empty) ||
                    (textBoxSSN.Text == String.Empty && textBoxFirstName.Text == String.Empty && textBoxLastName.Text == String.Empty
                    && textBoxCasinoName.Text == String.Empty && textBoxCasinoState.Text == String.Empty))
                {
                    MessageBox.Show("Please complete all player information fields.", "Input Error!");
                }
                else
                {
                    // if all textboxes are completed, assign to variables
                    myplayer.SocialSecurityNumber = textBoxSSN.Text;
                    myplayer.FirstName = textBoxFirstName.Text;
                    myplayer.LastName = textBoxLastName.Text;
                    mycasino.CasinoName = textBoxCasinoName.Text;
                    mycasino.CasinoState = textBoxCasinoState.Text;

                    // writing record to text file
                    writer.WriteLine(myplayer.ToString() + mycasino.ToString());

                    // if record is successfully written, display messagebox
                    MessageBox.Show("Wrote " + myplayer.FirstName.ToString() + ' ' + myplayer.LastName.ToString() + " to file with winnings totaling " + mywinnings.TotalWinnings.ToString("C2") + ".", "File Written");
                }
***************************ERROR HERE***************************
                // read weekly winnings input and assign to appropriate array position; test for empty inputs and assign default value of 0 if empty
                // Week1
                if (textBoxWeek1Winnings.Text == String.Empty)
                {
                    mywinnings.ReadWinningsIntoArray("0", 0);
                }
                else mywinnings.ReadWinningsIntoArray(textBoxWeek1Winnings.Text, 0);

                //// Week2
                //if (textBoxWeek2Winnings.Text == String.Empty)
                //{
                //    mywinnings.ReadWinningsIntoArray("0", 1);
                //}
                //else mywinnings.ReadWinningsIntoArray(textBoxWeek2Winnings.Text, 1);

                //// Week3
                //if (textBoxWeek3Winnings.Text == String.Empty)
                //{
                //    mywinnings.ReadWinningsIntoArray("0", 2);
                //}
                //else mywinnings.ReadWinningsIntoArray(textBoxWeek3Winnings.Text, 2);

                //// Week4
                //if (textBoxWeek2Winnings.Text == String.Empty)
                //{
                //    mywinnings.ReadWinningsIntoArray("0", 3);
                //}
                //else mywinnings.ReadWinningsIntoArray(textBoxWeek1Winnings.Text, 3);

                //// Week5
                //if (textBoxWeek2Winnings.Text == String.Empty)
                //{
                //    mywinnings.ReadWinningsIntoArray("0", 4);
                //}
                //else mywinnings.ReadWinningsIntoArray(textBoxWeek1Winnings.Text, 4);

                //// Week6
                //if (textBoxWeek2Winnings.Text == String.Empty)
                //{
                //    mywinnings.ReadWinningsIntoArray("0", 5);
                //}
                //else mywinnings.ReadWinningsIntoArray(textBoxWeek1Winnings.Text, 5);

                //// Week7
                //if (textBoxWeek2Winnings.Text == String.Empty)
                //{
                //    mywinnings.ReadWinningsIntoArray("0", 6);
                //}
                //else mywinnings.ReadWinningsIntoArray(textBoxWeek1Winnings.Text, 6);

                //// Week8
                //if (textBoxWeek2Winnings.Text == String.Empty)
                //{
                //    mywinnings.ReadWinningsIntoArray("0", 7);
                //}
                //else mywinnings.ReadWinningsIntoArray(textBoxWeek1Winnings.Text, 7);

                //// calculate total winnings by summing WeeklyWinnings array values and assigning to TotalWinnings
                //mywinnings.TotalWinnings = mywinnings.WeeklyWinnings.Sum();
            }
            catch (FormatException)
            {
                // if format exception is thrown in try, display messagebox with message
                MessageBox.Show("Winnings must be entered at xx.xx (e.g. 34.56).", "Input Error!");
            }
            catch (Exception f)
            {
                // if exception is thrown in try, display messagebox with message
                MessageBox.Show(f.Message, "Error!");
            }

            // clear form textboxes
            ClearTextBoxes();
            writer.Close();
        }

        // "Enter/Update Player" tab Exit button: closes file streams and quits the application
        private void buttonExit_Click(object sender, EventArgs e)
        {
            // closing file streams
            reader.Close();
            inFile.Close();
            writer.Close();
            outFile.Close();

            // close application
            Application.Exit();
        }

        // "Player List" tab View Player Winnings button: read file records, display records sorted by total winnings descending
        private void buttonRead_Click(object sender, EventArgs e)
        {   
            // if file exists
            if (!(File.Exists(FILEPATH + FILENAME)))
            {
                // if file does not exist, display messagebox
                MessageBox.Show("File does not exist.", "File Does Not Exist!");
            }
            else
            {
                string[] fields;

                // read first record in file
                string recordIn = reader.ReadLine();

                listBoxOutputRecords.Items.Add("First Name\tLast Name\tCasino Name\tCasino State\tTotal Winnings\t");

                while (recordIn != null)
                {
                    // split record into array and assign
                    fields = recordIn.Split(DELIM);
                    myplayer.SocialSecurityNumber = fields[0];
                    myplayer.FirstName = fields[1];
                    myplayer.LastName = fields[2];
                    mycasino.CasinoName = fields[3];
                    mycasino.CasinoState = fields[4];

                    // output record to listbox
                    listBoxOutputRecords.Items.Add(myplayer.FirstName + "\t\t" + myplayer.LastName + "\t\t" + mycasino.CasinoName + "\t\t" + mycasino.CasinoState + "\t\t");

                    // read next record in file
                    recordIn = reader.ReadLine();
                    }
            }

            // return file position to 0
            inFile.Seek(0, SeekOrigin.Begin);
        }

        // "Player List" tab Exit button: call buttonExit_Click method
        private void buttonExit2_Click(object sender, EventArgs e)
        {
            // call buttonExit_Click method
            buttonExit_Click(sender, e);
        }

        // method to clear listbox items when "Player List" tab is left
        private void tabPagePlayerList_Leave(object sender, EventArgs e)
        {
            // clear listbox items
            listBoxOutputRecords.Items.Clear();
        }

        // method to clear textbox controls
        private void ClearTextBoxes()
        {
            Action<Control.ControlCollection> func = null;

            func = (controls) =>
            {
                foreach (Control control in controls)
                    if (control is TextBox)
                        (control as TextBox).Clear();
                    else
                        func(control.Controls);
            };

            func(Controls);
        }
    }
}

我的班级代码:

class Person
{
    // SocialSecurityNumber, FirstName, LastName properties
    public string SocialSecurityNumber { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }

    // overridden ToString() method to return string output
    public override string ToString()
    {
        return (SocialSecurityNumber + ',' + FirstName + ',' + LastName + ',');
    }
}

// Location class
class Location
{
    // CasinoName and CasinoState properties
    public string CasinoName { get; set; }
    public string CasinoState { get; set; }

    // overridden ToString() method to return string output
    public override string ToString()
    {
        return (CasinoName + ',' + CasinoState + ',');
    }
}

// Winnings class
class Winnings
{
    double[] weeklyWinnings = new double[8];

    // WeeklyWinnings and TotalWinnings properties
    public double[] WeeklyWinnings { get; set; }
    public double TotalWinnings { get; set; }

    // overridden ToString() method to return string output
    public override string ToString()
    {
        return (  WeeklyWinnings[0].ToString("C2") + ','
                + WeeklyWinnings[1].ToString("C2") + ','
                + WeeklyWinnings[2].ToString("C2") + ','
                + WeeklyWinnings[3].ToString("C2") + ','
                + WeeklyWinnings[4].ToString("C2") + ','
                + WeeklyWinnings[5].ToString("C2") + ','
                + WeeklyWinnings[6].ToString("C2") + ','
                + WeeklyWinnings[7].ToString("C2") + ','
                + TotalWinnings.ToString("C2"));
    }

    // method to read textbox winnings inputs into the array
    public void ReadWinningsIntoArray(string textBoxText, int position)
    {
        double value;
        if (double.TryParse(textBoxText, out value))
            WeeklyWinnings[position] = Convert.ToDouble(value);
    }
}

2 个答案:

答案 0 :(得分:0)

是否在设计器文件中正确定义了textBoxWeek1Winnings?如果不是,则null是因为此变量未在任何地方定义,这就是问题。


我认为在表单的设计视图中,您应该能够看到奖金的文本框名称,这是您未正确设置的内容。在声明一个新的文本框

Dotnetperls有一个例子,可能有助于考虑你如何编码,因为我认为你在这里错过了一些相对简单的东西。

答案 1 :(得分:0)

您可以使用File.ReadAllLines()File.WriteAllLines()方法大大简化您的代码。