Чтение данных из файла - PullRequest
0 голосов
/ 19 марта 2011

Вот ссылка, если вы хотите скачать приложение:

Простое банковское приложение

Текстовый файл с данными для чтения

Я пытаюсь создать простое банковское приложение, которое считывает данные из текстового файла. До сих пор мне удалось прочитать всех клиентов, которых 20 из них. Тем не менее, при чтении в учетных записях и транзакциях он читает только в 20, а в текстовом файле их намного больше.

Вот что у меня есть. Я думаю, что это как-то связано с вложенным циклом в методе getNextCustomer.

using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace e_SOFT_Banking
{
    public partial class Form1 : Form
    {
        public static ArrayList bankDetails = new ArrayList();
        public static ArrayList accDetails = new ArrayList();
        public static ArrayList tranDetails = new ArrayList();

        string inputDataFile = @"C:\e-SOFT_v1.txt";

        const int numCustItems = 14;
        const int numAccItems = 7;
        const int numTransItems = 5;

        public Form1()
        {
            InitializeComponent();
            setUpBank();
        }

        private void btnShowData_Click_1(object sender, EventArgs e)
        {
            showListsOfCust();
        }

        private void setUpBank()
        {
            readData();
        }

        private void showListsOfCust()
        {
            listBox1.Items.Clear();

            foreach (Customer c in bankDetails)
                listBox1.Items.Add(c.getCustomerNumber() + " " + c.getCustomerTitle() + " " + c.getFirstName()
                                   + " " + c.getInitials() + " " + c.getSurname() + " " + c.getDateOfBirth()
                                   + " " + c.getHouseNameNumber() + " " + c.getStreetName() + " " + c.getArea()
                                   + " " + c.getCityTown() + " " + c.getCounty() + " " + c.getPostcode()
                                   + " " + c.getPassword() + " " + c.getNumberAccounts());

            foreach (Account a in accDetails)
                listBox1.Items.Add(a.getAccSort() + " " + a.getAccNumber() + " " + a.getAccNick() + " " + a.getAccDate()
                                   + " " + a.getAccCurBal() + " " + a.getAccOverDraft() + " " + a.getAccNumTrans());

            foreach (Transaction t in tranDetails)
                listBox1.Items.Add(t.getDate() + " " + t.getType() + " " + t.getDescription() + " " + t.getAmount()
                                   + " " + t.getBalAfter());
        }

        private void readData()
        {
            StreamReader readerIn = null;
            Transaction curTrans;
            Account curAcc;
            Customer curCust;
            bool anyMoreData;
            string[] customerData = new string[numCustItems];
            string[] accountData = new string[numAccItems];
            string[] transactionData = new string[numTransItems];

            if (readOK(inputDataFile, ref readerIn))
            {
                anyMoreData = getNextCustomer(readerIn, customerData, accountData, transactionData);

                while (anyMoreData == true)
                {
                    curCust = new Customer(customerData[0], customerData[1], customerData[2], customerData[3], customerData[4],
                                           customerData[5], customerData[6], customerData[7], customerData[8], customerData[9],
                                           customerData[10], customerData[11], customerData[12], customerData[13]);

                    curAcc = new Account(accountData[0], accountData[1], accountData[2], accountData[3], accountData[4],
                                         accountData[5], accountData[6]);

                    curTrans = new Transaction(transactionData[0], transactionData[1], transactionData[2], transactionData[3], 
                                               transactionData[4]);

                    bankDetails.Add(curCust);
                    accDetails.Add(curAcc);
                    tranDetails.Add(curTrans);

                    anyMoreData = getNextCustomer(readerIn, customerData, accountData, transactionData);
                }

                if (readerIn != null)
                    readerIn.Close();
            }
        }

        private bool getNextCustomer(StreamReader inNext, string[] nextCustomerData, string[] nextAccountData, string[] nextTransactionData)
        {
            string nextLine;
            int numCItems = nextCustomerData.Count();
            int numAItems = nextAccountData.Count();
            int numTItems = nextTransactionData.Count();

            for (int i = 0; i < numCItems; i++)
            {
                nextLine = inNext.ReadLine();
                if (nextLine != null)
                {
                    nextCustomerData[i] = nextLine;
                    if (i == 13)
                    {
                        int cItems = Convert.ToInt32(nextCustomerData[13]);
                        for (int q = 0; q < cItems; q++)
                        {
                            for (int a = 0; a < numAItems; a++)
                            {
                                nextLine = inNext.ReadLine();
                                nextAccountData[a] = nextLine;
                                if (a == 6)
                                {
                                    int aItems = Convert.ToInt32(nextAccountData[6]);
                                    for (int w = 0; w < aItems; w++)
                                    {
                                        for (int t = 0; t < numTItems; t++)
                                        {
                                            nextLine = inNext.ReadLine();
                                            nextTransactionData[t] = nextLine;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                else
                    return false;
            }
            return true;
        }

        private bool readOK(string readFile, ref StreamReader readerIn)
        {
            try
            {
                readerIn = new StreamReader(readFile);
                return true;
            }

            catch (FileNotFoundException notFound)
            {
                MessageBox.Show("ERROR Opening file (when reading data in)" + " - File could not be found.\n" + notFound.Message);
                return false;
            }

            catch (Exception e)
            {
                MessageBox.Show("ERROR Opening File (when reading data in)" + "- Operation failed.\n" + e.Message);
                return false;
            }
        }
    }
}

У меня также есть три класса: один для клиентов, один для счетов и один для транзакций, которые следуют в этом порядке.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace e_SOFT_Banking
{
    class Customer
    {
        private string customerNumber;
        private string customerTitle;
        private string firstName;
        private string initials;  //not required - defaults to null
        private string surname;
        private string dateOfBirth;
        private string houseNameNumber;
        private string streetName;
        private string area; //not required - defaults to null
        private string cityTown;
        private string county;
        private string postcode;
        private string password;
        private int numberAccounts;

        public Customer(string theCustomerNumber, string theCustomerTitle, string theFirstName, string theInitials, string theSurname, string theDateOfBirth, string theHouseNameNumber, string theStreetName, string theArea, string theCityTown, string theCounty, string thePostcode, string thePassword, string theNumberAccounts)
        {
            customerNumber = theCustomerNumber;
            customerTitle = theCustomerTitle;
            firstName = theFirstName;
            initials = theInitials;
            surname = theSurname;
            dateOfBirth = theDateOfBirth;
            houseNameNumber = theHouseNameNumber;
            streetName = theStreetName;
            area = theArea;
            cityTown = theCityTown;
            county = theCounty;
            postcode = thePostcode;
            password = thePassword;
            setNumberAccounts(theNumberAccounts);

        }

        public string getCustomerNumber()
        {
            return customerNumber;
        }

        public string getCustomerTitle()
        {
            return customerTitle;
        }

        public string getFirstName()
        {
            return firstName;
        }

        public string getInitials()
        {
            return initials;
        }

        public string getSurname()
        {
            return surname;
        }

        public string getDateOfBirth()
        {
            return dateOfBirth;
        }

        public string getHouseNameNumber()
        {
            return houseNameNumber;
        }

        public string getStreetName()
        {
            return streetName;
        }

        public string getArea()
        {
            return area;
        }

        public string getCityTown()
        {
            return cityTown;
        }

        public string getCounty()
        {
            return county;
        }

        public string getPostcode()
        {
            return postcode;
        }

        public string getPassword()
        {
            return password;
        }

        public int getNumberAccounts()
        {
            return numberAccounts;
        }


        public void setCustomerNumber(string inCustomerNumber)
        {
            customerNumber = inCustomerNumber;
        }

        public void setCustomerTitle(string inCustomerTitle)
        {
            customerTitle = inCustomerTitle;
        }

        public void setFirstName(string inFirstName)
        {
            firstName = inFirstName;
        }

        public void setInitials(string inInitials)
        {
            initials = inInitials;
        }

        public void setSurname(string inSurname)
        {
            surname = inSurname;
        }

        public void setDateOfBirth(string inDateOfBirth)
        {
            dateOfBirth = inDateOfBirth;
        }

        public void setHouseNameNumber(string inHouseNameNumber)
        {
            houseNameNumber = inHouseNameNumber;
        }

        public void setStreetName(string inStreetName)
        {
            streetName = inStreetName;
        }

        public void setArea(string inArea)
        {
            area = inArea;
        }

        public void setCityTown(string inCityTown)
        {
            cityTown = inCityTown;
        }

        public void setCounty(string inCounty)
        {
            county = inCounty;
        }

        public void setPostcode(string inPostcode)
        {
            postcode = inPostcode;
        }

        public void setPassword(string inPassword)
        {
            password = inPassword;
        }

        public void setNumberAccounts(string inNumberAccounts)
        {
            try
            {
                numberAccounts = Convert.ToInt32(inNumberAccounts);
            }
            catch (FormatException invalidInput)
            {
                System.Windows.Forms.MessageBox.Show("ERROR" + invalidInput.Message + "Please enter a valid number");
            }
        }

    }
}

Счета:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace e_SOFT_Banking
{
    class Account
    {
        private string accSort;
        private Int64 accNumber;
        private string accNick;
        private string accDate;  //not required - defaults to null
        private double accCurBal;
        private double accOverDraft;
        private int accNumTrans;

        public Account(string theAccSort, string theAccNumber, string theAccNick, 
                       string theAccDate, string theAccCurBal, string theAccOverDraft, 
                       string theAccNumTrans)
        {
            accSort = theAccSort;
            setAccNumber(theAccNumber);
            accNick = theAccNick;
            accDate = theAccDate;
            setAccCurBal(theAccCurBal);
            setAccOverDraft(theAccOverDraft);
            setAccNumTrans(theAccNumTrans);
        }

        public string getAccSort()
        {
            return accSort;
        }

        public long getAccNumber()
        {
            return accNumber;
        }

        public string getAccNick()
        {
            return accNick;
        }

        public string getAccDate()
        {
            return accDate;
        }

        public double getAccCurBal()
        {
            return accCurBal;
        }

        public double getAccOverDraft()
        {
            return accOverDraft;
        }

        public int getAccNumTrans()
        {
            return accNumTrans;
        }


        public void setAccSort(string inAccSort)
        {
            accSort = inAccSort;
        }

        public void setAccNumber(string inAccNumber)
        {
            try
            {
                accNumber = Convert.ToInt64(inAccNumber);
            }
            catch (FormatException invalidInput)
            {
                System.Windows.Forms.MessageBox.Show("ERROR" + invalidInput.Message + "Please enter a valid number");
            }
        }

        public void setAccNick(string inAccNick)
        {
            accNick = inAccNick;
        }

        public void setAccDate(string inAccDate)
        {
            accDate = inAccDate;
        }

        public void setAccCurBal(string inAccCurBal)
        {
            try
            {
                accCurBal = Convert.ToDouble(inAccCurBal);
            }
            catch (FormatException invalidInput)
            {
                System.Windows.Forms.MessageBox.Show("ERROR" + invalidInput.Message + "Please enter a valid number");
            }
        }

        public void setAccOverDraft(string inAccOverDraft)
        {
            try
            {
                accOverDraft = Convert.ToDouble(inAccOverDraft);
            }
            catch (FormatException invalidInput)
            {
                System.Windows.Forms.MessageBox.Show("ERROR" + invalidInput.Message + "Please enter a valid number");
            }
        }

        public void setAccNumTrans(string inAccNumTrans)
        {
            try
            {
                accNumTrans = Convert.ToInt32(inAccNumTrans);
            }
            catch (FormatException invalidInput)
            {
                System.Windows.Forms.MessageBox.Show("ERROR" + invalidInput.Message + "Please enter a valid number");
            }
        }
    }
}

Сделки:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace e_SOFT_Banking
{
    class Transaction
    {
        private string date;
        private string type;
        private string description;
        private double amount;  //not required - defaults to null
        private double balAfter;


        public Transaction(string theDate, string theType, string theDescription,
                       string theAmount, string theBalAfter)
        {
            date = theDate;
            type = theType;
            description = theDescription;
            setAmount(theAmount);
            setBalAfter(theBalAfter);
        }

        public string getDate()
        {
            return date;
        }

        public string getType()
        {
            return type;
        }

        public string getDescription()
        {
            return description;
        }

        public double getAmount()
        {
            return amount;
        }

        public double getBalAfter()
        {
            return balAfter;
        }

        public void setDate(string inDate)
        {
            date = inDate;
        }

        public void setType(string inType)
        {
            type = inType;
        }

        public void setDescription(string inDescription)
        {
            description = inDescription;
        }

        public void setAmount(string inAmount)
        {
            try
            {
                amount = Convert.ToDouble(inAmount);
            }
            catch (FormatException invalidInput)
            {
                System.Windows.Forms.MessageBox.Show("ERROR" + invalidInput.Message + "Please enter a valid number");
            }
        }

        public void setBalAfter(string inBalAfter)
        {
            try
            {
                balAfter = Convert.ToDouble(inBalAfter);
            }
            catch (FormatException invalidInput)
            {
                System.Windows.Forms.MessageBox.Show("ERROR" + invalidInput.Message + "Please enter a valid number");
            }
        }
    }
}

Любая помощь с благодарностью.

1 Ответ

0 голосов
/ 21 марта 2011

Ваша проблема начинается со следующего

string[] customerData = new string[numCustItems];
string[] accountData = new string[numAccItems];
string[] transactionData = new string[numTransItems];

С этой структурой и вызовом

anyMoreData = getNextCustomer(readerIn, customerData, accountData, transactionData);

вы получите только одну accountData и одну транзакциюData для одного клиента.

Пожалуйста, измените дизайн своего кода, чтобы объекты данных знали, как считывать свои данные из потока данных.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...