I have an employee management system which I'm trying to build in c# console application whereas im able to add a new employee.
but I'm not sure on how can I delete a employee from the list.
I have to put together both method then it works.
it seem like i'm unable to call the obj (emp) from my removeEmployee method
Main class
using System;
namespace HRM
{
class Program
{
static void Main(string[] args)
{
manageEmp emp = new manageEmp();
emp.addEmployee();
emp.removeEmployee();
}
}
}
Employee Class
using System;
using System.Collections.Generic;
namespace HRM
{
public class Employee
{
private String empID;
private String empFirstName;
private String empLastName;
private String empDep;
private String empDOB;
private String empAddress;
private int PostalCode;
private double empSal;
public Employee()
{
}
public Employee(String aempID, string aempFirstName, string aempLasttName, string aempDep, String aEmpDOB, string aempAddress, int aPostalCode, double aempSal)
{
this.EmpID = aempID;
this.EmpFirstName = aempFirstName;
this.EmpLastName = aempLasttName;
this.EmpDep = aempDep;
this.EmpDOB = aEmpDOB;
this.EmpAddress = aempAddress;
this.PostalCode1 = aPostalCode;
this.EmpSal = aempSal;
}
public string EmpID { get => empID; set => empID = value; }
public string EmpFirstName { get => empFirstName; set => empFirstName = value; }
public string EmpLastName { get => empLastName; set => empLastName = value; }
public string EmpDep { get => empDep; set => empDep = value; }
public string EmpDOB { get => empDOB; set => empDOB = value; }
public string EmpAddress { get => empAddress; set => empAddress = value; }
public int PostalCode1 { get => PostalCode; set => PostalCode = value; }
public double EmpSal { get => empSal; set => empSal = value; }
public List<Employee> El { get => el; set => el = value; }
public override string ToString()
{
return "Employment ID : " + empID + "\n"
+ "FirstName : " + EmpFirstName + "\n"
+ "LastName : " + EmpLastName + "\n"
+ "Department : " + EmpDep + "\n"
+ "Date of Birth: " + EmpDOB + "\n"
+ "Address : " + EmpAddress + "\n"
+ "PostalCode : " + PostalCode1 + "\n"
+ "empSal : " + EmpSal + "\n";
}
}
}
manageEmp class
using System;
using System.Collections.Generic;
namespace HRM
{
public class manageEmp
{
private List<Employee> el = new List<Employee>();
public List<Employee> El { get => el; set => el = value; }
public void addEmployee()
{
Console.WriteLine("===================================" + "\n");
Console.WriteLine("Add an Employee");
Console.WriteLine("===================================" + "\n");
Console.WriteLine("");
Console.WriteLine("Please enter your Employment ID");
String eID = Console.ReadLine();
Console.WriteLine("Please enter your First Name");
String eFirstName = Console.ReadLine();
Console.WriteLine("Please enter your Last Name");
String eLasttName = Console.ReadLine();
Console.WriteLine("Please entter your department");
String eDep = Console.ReadLine();
Console.WriteLine("Please enter your Date of Birth");
String eDOB = Console.ReadLine();
Console.WriteLine("Please entter your Address");
String eAddress = Console.ReadLine();
Console.WriteLine("Please enter your Postal Code");
int ePostalCode = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Please enter your Salary");
double eSal = Convert.ToDouble(Console.ReadLine());
Employee emp = new Employee(eID, eFirstName, eLasttName, eDep, eDOB, eAddress, ePostalCode, eSal);
emp.El.Add(emp);
}
public void viewEmployee()
{
Employee nemp = new Employee();
nemp.El.ForEach(Console.WriteLine);
}
public void removeEmployee()
{
Console.WriteLine("Please enter a employee Id to be deleted");
String delemp = Console.ReadLine();
for (int i = 0; i < El.Count; i++)
{
emp = El[i];
if (delemp.Equals(eID))
{
el.Remove(emp);
}
Console.WriteLine(delemp + " Has been deleted sucessfully");
el.ForEach(Console.WriteLine);
}
}
}
}
Your problem is that your employee list is inside the employee class -- so each of the employees has its own list of employees -- and that list only contains that single employee.
In the function RemoveEmployee you are creating a new manageEmp object. As the word 'new' implies, this is a different, newly created manageEmp with its own, newly created List<Employee> which doesn't contain any items.
Further, you have declared the function as public void removeEmployee(string eID) so you can't call it with the line emp.removeEmployee().
Related
I have an array that is populated with user input and needs to be sorted according to a particular property. I have looked at similar questions on here but it does not seem to help my specific situation and so far nothing I've tried has worked.
The properties for the array are defined in a separate class.
It's a basic program for loading employees onto a system and the output needs to be sorted according to their salary.
*Note that I am a student and I am possibly missing something very basic.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.AccessControl;
using System.Text;
using System.Threading.Tasks;
namespace Instantiating_Objects
{
class Program
{
static void Main(string[] args)
{
//Cleaner cleaner = new Cleaner(); // Instantiantion
// Object Array
Cleaner[] clean = new Cleaner[3]; // Empty Object Array
Cleaner[] loadedCleaners = LoadCleaners(clean);
for (int i = 0; i < loadedCleaners.Length; i++)
{
Console.WriteLine(" ");
Console.WriteLine(loadedCleaners[i].Display() + "\n Salary: R" + loadedCleaners[i].CalcSalary());
}
Console.ReadKey();
}
public static Cleaner[] LoadCleaners(Cleaner[] cleaner)
{
for (int i = 0; i < cleaner.Length; i++)
{
Console.WriteLine("Enter your staff number");
long id = Convert.ToInt64(Console.ReadLine());
Console.WriteLine("Enter your last name");
string lname = Console.ReadLine();
Console.WriteLine("Enter your first name");
string fname = Console.ReadLine();
Console.WriteLine("Enter your contact number");
int contact = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter your number of hours worked");
int hours = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("");
// Populating object array
cleaner[i] = new Cleaner(id, fname, lname, contact, hours);
}
Array.Sort(, )
return cleaner;
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Instantiating_Objects
{
class Cleaner
{
private long staffNo;
private string lastName;
private string fName;
private int contact;
private int noHours;
private double rate = 380.00;
public Cleaner() { }
public Cleaner(long staffId, string name, string surname, int number, int hours)
{
this.contact = number;
this.fName = surname;
this.lastName = name;
this.staffNo = staffId;
this.noHours = hours;
}
public int GetHours() { return noHours;}
public long GetStaffID() { return staffNo; }
public string GetSurname() { return lastName; }
public string GetName() { return fName; }
public int GetNumber() { return contact; }
// Calculate Salary
public double CalcSalary()
{
double salary = 0;
if(GetHours() > 0 && GetHours() <= 50)
{
salary = GetHours() * rate;
}
else if (GetHours() > 50)
{
salary = (GetHours() * rate) + 5000;
}
return salary;
}
public string Display()
{
return "\n Staff no: " + GetStaffID() + "\n Surname" + GetSurname()
+ "\n Name: " + GetName() + "\n Contact no: " + GetNumber();
}
}
}
I will combine Legacy code and Ňɏssa Pøngjǣrdenlarp into one.
First thing as Ňɏssa Pøngjǣrdenlarp said your Cleaner class has no properties.
I removed all your methods and changed it with properties instead
public class Cleaner
{
public Cleaner(long staffId, string name, string surname, int number, int hours)
{
StaffNo = staffId;
FName = name;
LastName = surname;
Contact = number;
NoHours = hours;
}
public long StaffNo { get; set; }
public string LastName { get; set; }
public string FName { get; set; }
public int Contact { get; set; }
public int NoHours { get; set; }
public double Rate => 380.00;
public double Salary
{
get
{
double salary = 0;
if (NoHours > 0 && NoHours <= 50)
{
salary = NoHours * Rate;
}
else if (NoHours > 50)
{
salary = (NoHours * Rate) + 5000;
}
return salary;
}
}
public override string ToString()
{
return "\n Staff no: " + StaffNo + "\n Surname" + LastName
+ "\n Name: " + FName + "\n Contact no: " + Contact;
}
}
Now that we have fixed the class we can look at the Program Main method.
Because we changed the cleaner class to use properties instead we can easily use Linq to orderby
private static void Main(string[] args)
{
//Cleaner cleaner = new Cleaner(); // Instantiantion
// Object Array
var clean = new Cleaner[3]; // Empty Object Array
var loadedCleaners = LoadCleaners(clean).OrderBy(_ => _.Salary).ToArray();
foreach (Cleaner v in loadedCleaners)
{
Console.WriteLine(" ");
Console.WriteLine(v + "\n Salary: R" + v.Salary);
}
Console.ReadKey();
}
You will notice that on this line
var loadedCleaners = LoadCleaners(clean).OrderBy(_ => _.Salary).ToArray();
that i am using Linq to order the Salary.
For more on Linq check out the following docs https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/linq/
On a side note
I would say consistency is key, this will keep your code clean.
Look at the following example, the naming convention is inconsistent
public Cleaner(long staffId, string name, string surname, int number, int hours)
{
StaffNo = staffId;
FName = name;
LastName = surname;
Contact = number;
NoHours = hours;
}
Nice, clean and easy to follow
public Cleaner(long staffId, string firstName, string lastName, int number, int hours)
{
StaffId = staffId;
FirstName = firstName;
LastName = lastName;
Number = number;
Hours = hours;
}
I'm fairly new to C# and I have created a small program with 2 classes ( 1 being the class containing the main method).
Instructor class:
namespace Exercise4
{
class Account
{
public long accountNo { set; get; }
public double balance { set; get; }
public string [] payees { set; get; }
public long [] payeesAccount { set; get; }
public Account()
{
this.accountNo = 0L;
this.balance = 0.0;
}
public Account(long accountNo,double balance)
{
this.accountNo = accountNo;
this.balance = balance;
}
public Account(long accountNo, double balance, string [] payees, long [] payeesAccount)
{
this.accountNo = accountNo;
this.balance = balance;
this.payees = payees;
this.payeesAccount = payeesAccount;
}
public int DebitAmount(double amount)
{
if ((this.balance - amount) <= this.balance)
return 1;
else
return 0;
}
public int TransferMoney(long payeeAccountNo, double amount)
{
if (payeesAccount.Contains(payeeAccountNo))
return DebitAmount(amount);
else
return -1;
}
public int TransferMoeny(string nickName,double amount)
{
if (payees.Contains(nickName))
return DebitAmount(amount);
else
return -1;
}
public string ToString()
{
string output = "";
output += "\nAccount Number: " + this.accountNo;
output += "\nBalance: " + this.balance;
output += "\nPayee: " + this.payees;
output += "\nPayee Account: " + this.payeesAccount;
return output;
}
}
}
Main method class:
namespace Exercise4
{
class Program
{
static void Main(string[] args)
{
string [] payee = new [] {"Oli"};
long[] payeesAccount = new[] {1000L};
Account reg = new Account(1000,100.00,payee,payeesAccount);
Console.WriteLine(reg.ToString());
}
}
}
I'm trying to print the value(Payee: Oli, Payee Account: 1000 )of the arrays instead of:
Account Number: 1000
Balance: 100
Payee: System.String[]
Payee Account: System.Int64[]
Any thoughts?
Thanks
You can use string.Join for such purposes
Try to define your method ToString() like this:
public override string ToString()
{
string output = "";
output += "\nAccount Number: " + this.accountNo;
output += "\nBalance: " + this.balance;
output += "\nPayee: " + string.Join(",", this.payees);
output += "\nPayee Account: " + string.Join(",", this.payeesAccount);
return output;
}
If you override the default method ToString() correctly then you can use it like this:
Console.WriteLine(reg);
Without the need to call it esplicitly.
And your overriden method should look like this, with string builder to create dynamic string properly:
public override string ToString()
{
var output = new StringBuilder();
output.Append("\nAccount Number: " + this.accountNo);
output.Append("\nBalance: " + this.balance);
output.Append("\nPayee: " + string.Join(", ", this.payees));
output.Append("\nPayee Account: " + string.Join(", ", this.payeesAccount));
return output.ToString();
}
And even better with C# 6.0+ using string interpolation:
public override string ToString()
{
var output = new StringBuilder();
output.Append($"Account Number: {accountNo}\n");
output.Append($"Balance: {balance}\n");
output.Append($"Payee: {string.Join(", ", payees)}\n");
output.Append($"Payee Account: {string.Join(", ", payeesAccount)}\n");
return output.ToString();
}
But I can advice you to review your class and decide if you realy need to have string[] instead of just string, as I can see you have only one payee and their account.
So I need to create this bank service. I have everything except I am trying to use the updated balance from a customer after a transaction such a withdraw or deposit. For example the customer starts off with $1000, and customer 1 deposits $300. The updated balance should be $1300, but once I do another transaction it goes back to the default $1000, instead of the new balance of $1300. The customers are in a list.
[ServiceContract(SessionMode=SessionMode.Allowed)]
public interface IBankService
{
[OperationContract]
string GetCustDetails(int act);
[OperationContract]
string WithdrawMoney(int act, double amt);
[OperationContract]
string DepositMoney(int act,double amt);
[OperationContract]
string ViewBalance(int act);
}
// Use a data contract as illustrated in the sample below to add composite types to service operations.
[DataContract]
public class Customer
{
private int accountNumber; private double viewBalance, depositMoney;
private string customerName, customerAddress;
public Customer(int act, string str_name, string adrs, double bal)
{
accountNumber = act;
customerName = str_name;
customerAddress = adrs;
viewBalance = bal;
}
[DataMember(Name = "Name")]
public string CustomerName
{
get { return customerName; }
set { customerName = value; }
}
[DataMember(Name = "Address")]
public string CustomerAddress
{
get { return customerAddress; }
set { customerAddress = value; }
}
[DataMember(Name = "Account")]
public int AccountNumber
{
get { return accountNumber; }
set { accountNumber = value; }
}
[DataMember(Name = "Balance", EmitDefaultValue = true)]
public double ViewBalance
{
get { return viewBalance; }
set
{
if (value <= 0.0)
viewBalance = 0.0;
else
viewBalance = value;
}
}
[DataMember(Name = "Credit")]
public double DepositMoney
{
get { return depositMoney; }
set { depositMoney = value; }
}
}
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)]
class BankService : IBankService
{
List<Customer> custList;
static double balance1 = 1000;
static double balance2 = 1000;
static double balance3 = 1000;
static double balance4 = 1000;
static double balance5 = 1000;
public BankService()
{
custList = new List<Customer>();
custList.Add(new Customer(100, "Jack", "404 Bay Avenue", balance1));
custList.Add(new Customer(200, "Jeff", "255 Wade Avenue",balance2));
custList.Add(new Customer(300, "Lou", "984 Leslie Road", balance3));
custList.Add(new Customer(400, "Johnson","1080 Queen Street", balance4));
custList.Add(new Customer(500, "Alex","777 Jane Street", balance5));
}
public string GetCustDetails(int act)
{
foreach (Customer cust in custList)
{
if (cust.AccountNumber == act)
{
return string.Format("Account Number: " + cust.AccountNumber + "\n" +
"Name: " + cust.CustomerName + "\n" +
"Address: " + cust.CustomerAddress + "\n" +
"Balance: $" + cust.ViewBalance);
}
} // end foreach
return string.Format("{0}", "Customer does not exists!");
}
//public string DepositMoney(int act, double amt)
//{
// string balance = null;
// foreach (Customer cust in custList)
// {
// if (cust.AccountNumber == act)
// {
// bal = bal + Dep;
// }
// }
// return balance;
//}
public string DepositMoney(int act, double amt)
{
foreach (Customer cust in custList)
{
if (cust.AccountNumber == act)
{
cust.ViewBalance = cust.ViewBalance + amt;
return string.Format("Account Number : " + cust.AccountNumber + "\n" +
"Name : " + cust.CustomerName + "\n" +
"Address : " + cust.CustomerAddress + "\n" +
"Balance :$ " + cust.ViewBalance);
}
}
return string.Format("{0}", "Customer does not exists!");
}
//public double WithdrawMoney(double widraw)
//{
// return bal = bal - widraw;
//}
// public double ViewBalance(int act)
//{
// return bal;
//}
public string WithdrawMoney(int act, double amt)
{
foreach (Customer cust in custList)
{
if (cust.AccountNumber == act)
{
cust.ViewBalance = cust.ViewBalance - amt;
return string.Format("Account Number : " + cust.AccountNumber + "\n" +
"Name : " + cust.CustomerName + "\n" +
"Address : " + cust.CustomerAddress + "\n" +
"Balance :$ " + cust.ViewBalance);
}
}
return string.Format("{0}", "Customer does not exists!");
}
public string ViewBalance(int act)
{
foreach (Customer cust in custList)
{
if (cust.AccountNumber == act)
{
return string.Format("Balance : $" + cust.ViewBalance);
}
}
return string.Format("{0}", "Customer does not exists!");
}
}
Each customer has their own account number that is already assigned.
How are you consuming this service ?
I mean to say how you are creating your client (can you post some code).
Following salient points are taken into account while consuming the service
Adding a service reference
Creating an instance of the client
Calling the web methods of the instance
I'm working on an exam app (c# console application)
The app asks the user to enter its name, I would like the app to read in that user's name and
print the user's details based on the details I've stored in the objects
For example:
If the user's name matches the name in this object:
students s3 = new students("Dee", "Scott", "Computing", 100m, 66.6m);
how could it print this user's details.
I've got a separate method that prints out the user's details
public string gradeDetails {
get { return FirstName + LastName + Course + FinalGrade; }
}
I cant figure out how to match the user input to corresponding object.
You can use the Console.Readline() method
public static void Main()
{
string line;
Console.WriteLine("Enter one or more lines of text (press CTRL+Z to exit):");
Console.WriteLine();
do {
Console.Write(" ");
line = Console.ReadLine();
if (line != null)
Console.WriteLine(" " + line);
} while (line != null);
Console.ReadLine();
Console.WriteLine(); or Console.Write();
I am not sure if that is what you are asking, but those are the calls to read and write.
This info is easily Google-able though.
The example below will do what you asked for. If you have any questions regarding the code I used then don't hesitate to ask.
class Student
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Course { get; set; }
public decimal FinalGrade { get; set; }
public Student(string firstName,
string lastName,
string course)
{
FirstName = firstName;
LastName = lastName;
Course = course;
FinalGrade = 0;
}
// This will first call the constructor above and then continue.
public Student(string firstName,
string lastName,
string course,
decimal finalGrade) : this(firstName, lastName, course)
{
FinalGrade = finalGrade;
}
// By overriding ToString we can use Console.WriteLine(student) directly.
public override string ToString()
{
return string.Format(#"FirstName: {0}, LastName: {1}, Course: {2}, FinalGrade: {3}",
FirstName,
LastName,
Course,
FinalGrade);
}
}
class Program
{
static void Main(string[] args)
{
// Create our students.
List<Student> students = new List<Student>
{
new Student("John", "Test", "Computing"),
new Student("Tim", "Test", "Computing", 8.25m)
};
string user = "";
do
{
Console.Clear();
Console.WriteLine("Please enter the name of the student:");
user = Console.ReadLine();
if (user.Equals("exit", StringComparison.OrdinalIgnoreCase))
break;
// Find the student or return null.
Student student = students.FirstOrDefault(s => s.FirstName.Equals(user, StringComparison.OrdinalIgnoreCase));
if (student != null)
{
Console.WriteLine("Student info:");
Console.WriteLine(student);
}
else
{
Console.WriteLine("Student '" + user + "' not found.");
}
Console.WriteLine();
// Wait until a key is pressed.
Console.WriteLine("Press a key to continue..");
Console.ReadKey(true);
} while (true);
}
}
Do something like this:
create a class called Student:
public class Student
{
public string Fname { get; set; }
public string LName { get; set; }
public string Course { get; set; }
public string FinalGrade { get; set; }
}
Then do this
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter you name:");
string name = Console.ReadLine();
Console.WriteLine(gradeDetails(name));
Console.ReadLine();
}
public static string gradeDetails(string name)
{
List<Student> students = new List<Student>()
{
new Student{ Fname = "Scott",LName ="Dee",Course = "Computing", FinalGrade = "66.66m"},
new Student{Fname = "Joe",LName = "Don",Course = "Chemestry", FinalGrade = "80.77m"}
};
var student = students.SingleOrDefault(s => s.LName.ToLower() == name.ToLower());
if (student!=null)
{
return student.Fname + "" + student.LName + "" + student.Course + "" + student.FinalGrade;
}
return string.Empty;
}
}
Ask user to enter name and print name
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace stackoverflow1
{
class Program
{
static void Main(string[] args)
{
string name;
Console.WriteLine("Enter your name : ");
name = Console.ReadLine();
Console.WriteLine("Hello " + name + " , Welcome to OOP!");
Console.ReadKey();
}
}
}
Here is link if you want to download application:
Simple banking app
Text file with data to read
I am trying to create a simple banking application that reads in data from a text file. So far i have managed to read in all the customers which there are 20 of them. However when reading in the accounts and transactions stuff it only reads in 20 but there is alot more in the text file.
Here is what i have so far. I think it has something to do with the nested for loop in the getNextCustomer method.
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;
}
}
}
}
I also have three classes one for customers, one for accounts and one for transactions, which follow in that order.
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");
}
}
}
}
Accounts:
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");
}
}
}
}
Transactions:
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");
}
}
}
}
Any help greatly appreciated.
Your problem start with the following
string[] customerData = new string[numCustItems];
string[] accountData = new string[numAccItems];
string[] transactionData = new string[numTransItems];
With this structure and the call
anyMoreData = getNextCustomer(readerIn, customerData, accountData, transactionData);
you will get only one accountData and one transactionData for one customer.
Please redesign your code, so that your data objects know how to read theirselve from the datastream.