简体   繁体   中英

How to store specific lines in a text file in a array (i.e 2 seperate bank accounts)

I am doing a ATM project for my computer science class and we are required to make an ATM that stores and reads accounts in a text file. I am stuck trying to figure out how I can get an array in the program to store 4 lines from the text file (Account number, Name, NIP and total balance) and be able to access them when the user enters the correct account number.

RBC001 (Account Number)
Ariel Bendahan (Name)
1337 (NIP)
50000 (Total Balance)
RBC002 (Same thing but second account)
John Baker (...)
6868 (...)
2500 (...)

^ This is the text document for reference.

I tried to make an array that stores all bank account BankAccount[] tabBankAccounts = new BankAccount[200]; (The array in question) but I just don't know how to exactly store 4 lines a code in each index of the array.

StreamReader myfile = new StreamReader("AccountInfo.txt");
            Int16 i = 0;
            while (myfile.EndOfStream == false)
            {
                tabBankAccounts[i].AccountNumber = myfile.ReadLine();
                tabBankAccounts[i].Name = myfile.ReadLine();
                tabBankAccounts[i].NIP = Convert.ToInt16(myfile.ReadLine());
                tabBankAccounts[i].TotalBalance = Convert.ToInt32(myfile.ReadLine());
            }
            myfile.Close();

^ The programming reading the text document.

This is more like a continuation of my first question so I'm sorry if my recent posts felt like spam.

when you initialize an array with BankAccount[] tabBankAccounts = new BankAccount[200]; , all the elements in the array are still null, which means first you have to create an instance for each bank account in order to set the AccountNumber etc.

Basically like this:

            StreamReader myfile = new StreamReader("AccountInfo.txt");
            Int16 i = 0;
            while (myfile.EndOfStream == false)
            {
                BankAccount bankAccount = new BankAccount();

                bankAccount.AccountNumber = myfile.ReadLine();
                bankAccount.Name = myfile.ReadLine();
                bankAccount.NIP = Convert.ToInt16(myfile.ReadLine());
                bankAccount.TotalBalance = Convert.ToInt32(myfile.ReadLine());

                tabBankAccounts[i] = bankAccount;
                i++;
            }
            myfile.Close();

also you forgot to increment i after each iteration, which means you would have only set the values of the first bank account

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM