class Leerling
{
public int Leeftijd { get; set; }
public decimal Cijfer { get; set; }
public string Naam { get; set; }
public string Achternaam { get; set; }
public List<Leerling> Studentenlijst { get; set; }
public Leerling()
{
Studentenlijst = new List<Leerling>();
}
public Leerling(int _leeftijd, int _cijfer, string _naam, string _achternaam)
{
Leeftijd = _leeftijd;
Cijfer = _cijfer;
Naam = _naam;
Achternaam = _achternaam;
}
public string ToonLeerling()
{
string output = "";
for (int i = 1; i < Studentenlijst.Count; i++)
{
if (Studentenlijst[i].Leeftijd <= 14)
{
Leerling objLeerling = (Leerling)Studentenlijst[i];
output = output + objLeerling.ToString();
}
}
return output;
}
public string ToonLeerlingouder()
{
string output = "";
for (int i = 1; i < Studentenlijst.Count; i++)
{
if (Studentenlijst[i].Leeftijd >= 15
)
{
Leerling objLeerling = (Leerling)Studentenlijst[i];
output = output + objLeerling.ToString();
}
}
return output;
}
public void addLeerling()
{
Leerling Leerling1 = new Leerling(18, 60, "Tom", "Lub");
Leerling Leerling2 = new Leerling(14, 50, "Kees", "Apenvlees");
Studentenlijst.Add((Leerling)Leerling1);
Studentenlijst.Add((Leerling)Leerling2);
}
public override string ToString()
{
return " Leeftijd " + Leeftijd + "\n Cijfer: " + Cijfer + "\n Naam: " + Naam + "\n Achternaam: " + Achternaam;
}
/*
Leerling l = new Leerling();
l.addLeerling();
Console.WriteLine(l.ToonLeerling().ToString());
Console.ReadLine();
l.addLeerling();
Console.WriteLine(l.ToonLeerlingouder().ToString());
Console.ReadLine();
*/
}
}
How do I get the values of leerling below 10?
You can try this
public List<String> ToonLeerlingJonger(){
List<String> LeerlingenJongerDan10 = new List<String>();
foreach(Leerling l in Studentenlijst){
if(l.Leeftijd < 10){
LeerlingenJongerDan10.add(l.ToString());
}
return LeerlingenJongerDan10;
}
}
Related
I have a SQlite based Xamarin Forms application on my Android Phone and Wear device. Syncing between my Phone and my Wear watch is performed according to my answer to another Question.
My database has the folowing tables Match and MatchStat:
public class Match
{
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
public DateTime MatchDate { get; set; }
public TimeSpan MatchTime { get; set; }
public string Home { get; set; }
public string Guest { get; set; }
public int HomeScore { get; set; }
public int GuestScore { get; set; }
public bool Active { get; set; }
public bool Done { get; set; }
public string HomeColor { get; set; }
public string GuestColor { get; set; }
public Match()
{ }
}
public class MatchStat
{
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
public int MatchId { get; set; }
public int ActionMin { get; set; }
public int HomeScore { get; set; }
public int GuestScore { get; set; }
public string ActionItem { get; set; }
public string PlayerName { get; set; }
public MatchStat()
{ }
}
If I want to sync my Match and all the MatchStat data from one device to the other I am doing it by mapping the data as strings in my MainActivity:
public async static void SendNewMatch(Match match, string path)
{
if (!client.IsConnected)
client.Connect();
await Task.Delay(200);
try
{
var request = PutDataMapRequest.Create(path);
var map = request.DataMap;
if (match != null)
{
map.PutString("Device", device);
map.PutString("Item", "AddMatch");
map.PutString("Home", match.Home);
map.PutString("Guest", match.Guest);
map.PutString("Active", match.Active.ToString());
map.PutString("Done", match.Done.ToString());
map.PutString("GuestScore", match.GuestScore.ToString());
map.PutString("HomeScore", match.HomeScore.ToString());
map.PutString("Date", match.MatchDate.Date.ToString());
map.PutString("Time", match.MatchTime.ToString());
map.PutLong("UpdatedAt", DateTime.UtcNow.Ticks);
await WearableClass.DataApi.PutDataItem(client, request.AsPutDataRequest());
}
request.UnregisterFromRuntime();
}
catch
{ }
finally
{
client.Disconnect();
}
}
public async static void SendMatchStat(MatchStat matchstat, Match match, int matchstatsize, string path)
{
if (!client.IsConnected)
client.Connect();
await Task.Delay(200);
try
{
var request = PutDataMapRequest.Create(path);
var map = request.DataMap;
MatchHelper mh = new MatchHelper();
if (matchstat != null)
{
map.PutString("Device", device);
map.PutString("Item", "MatchStat");
map.PutString("Home", match.Home);
map.PutString("Date", match.MatchDate.Date.ToString());
map.PutString("Time", match.MatchTime.ToString());
map.PutString("ActionItem", matchstat.ActionItem);
map.PutString("ActionMin", matchstat.ActionMin.ToString());
map.PutString("GuestScore", matchstat.GuestScore.ToString());
map.PutString("HomeScore", matchstat.HomeScore.ToString());
map.PutString("MatchStatSize", matchstatsize.ToString());
//map.PutString("PlayerName", matchstat.PlayerName.ToString());
map.PutLong("UpdatedAt", DateTime.UtcNow.Ticks);
await WearableClass.DataApi.PutDataItem(client, request.AsPutDataRequest());
}
request.UnregisterFromRuntime();
}
catch
{ }
finally
{
client.Disconnect();
}
}
public void ProcessMessage(Intent intent)
{
if (intent.GetStringExtra("Device") != device)
{
switch (intent.GetStringExtra("Item"))
{
case "AddMatch":
{
AddMatch(intent);
break;
}
case "MatchStat":
{
InsertMatchStat(intent);
break;
}
}
}
}
private void AddMatch(Intent intent)
{
MatchHelper mh = new MatchHelper();
if (bool.Parse(intent.GetStringExtra("Active")))
{
ObservableCollection<Match> activeMatches = mh.GetActiveMatches();
foreach (Match activeMatch in activeMatches)
{
mh.InactivateMatch(activeMatch);
}
}
Match newmatch = new Match();
newmatch.Home = intent.GetStringExtra("Home");
newmatch.Guest = intent.GetStringExtra("Guest");
newmatch.HomeColor = intent.GetStringExtra("HomeColor");
newmatch.GuestColor = intent.GetStringExtra("GuestColor");
newmatch.Active = bool.Parse(intent.GetStringExtra("Active"));
newmatch.Done = bool.Parse(intent.GetStringExtra("Done"));
newmatch.HomeScore = int.Parse(intent.GetStringExtra("HomeScore"));
newmatch.GuestScore = int.Parse(intent.GetStringExtra("GuestScore"));
newmatch.Active = bool.Parse(intent.GetStringExtra("Active"));
newmatch.Done = bool.Parse(intent.GetStringExtra("Done"));
newmatch.MatchDate = DateTime.Parse(intent.GetStringExtra("Date"));
newmatch.MatchTime = TimeSpan.Parse(intent.GetStringExtra("Time"));
mh.InsertMatch(newmatch);
}
private void InsertMatchStat(Intent intent)
{
MatchHelper mh = new MatchHelper();
Match match = mh.GetSpecificMatch(intent.GetStringExtra("Home"), DateTime.Parse(intent.GetStringExtra("Date")), TimeSpan.Parse(intent.GetStringExtra("Time")));
if (match != null)
{
MatchStat machstat = new MatchStat();
machstat.MatchId = match.Id;
machstat.ActionItem = intent.GetStringExtra("ActionItem");
machstat.ActionMin = int.Parse(intent.GetStringExtra("ActionMin"));
machstat.GuestScore = int.Parse(intent.GetStringExtra("GuestScore"));
machstat.HomeScore = int.Parse(intent.GetStringExtra("HomeScore"));
machstat.PlayerName = intent.GetStringExtra("PlayerName");
mh.InsertMatchStat(machstat);
}
}
In my WearService I have my OnDataChanged:
public override void OnDataChanged(DataEventBuffer dataEvents)
{
var dataEvent = Enumerable.Range(0, dataEvents.Count)
.Select(i => dataEvents.Get(i).JavaCast<IDataEvent>())
.FirstOrDefault(x => x.Type == DataEvent.TypeChanged && x.DataItem.Uri.Path.Equals(_syncPath));
if (dataEvent == null)
return;
//get data from wearable
var dataMapItem = DataMapItem.FromDataItem(dataEvent.DataItem);
var map = dataMapItem.DataMap;
Intent intent = new Intent();
intent.SetAction(Intent.ActionSend);
intent.PutExtra("Device", map.GetString("Device"));
intent.PutExtra("Item", map.GetString("Item"));
switch (map.GetString("Item"))
{
case "AddMatch":
{
intent.PutExtra("Home", map.GetString("Home"));
intent.PutExtra("Guest", map.GetString("Guest"));
intent.PutExtra("HomeColor", map.GetString("HomeColor"));
intent.PutExtra("GuestColor", map.GetString("GuestColor"));
intent.PutExtra("Active", map.GetString("Active"));
intent.PutExtra("Done", map.GetString("Done"));
intent.PutExtra("HomeScore", map.GetString("HomeScore"));
intent.PutExtra("GuestScore", map.GetString("GuestScore"));
intent.PutExtra("Date", map.GetString("Date"));
intent.PutExtra("Time", map.GetString("Time"));
LocalBroadcastManager.GetInstance(this).SendBroadcast(intent);
break;
}
case "MatchStat":
{
intent.PutExtra("Home", map.GetString("Home"));
intent.PutExtra("Date", map.GetString("Date"));
intent.PutExtra("Time", map.GetString("Time"));
intent.PutExtra("ActionItem", map.GetString("ActionItem"));
intent.PutExtra("ActionMin", map.GetString("ActionMin"));
intent.PutExtra("GuestScore", map.GetString("GuestScore"));
intent.PutExtra("HomeScore", map.GetString("HomeScore"));
intent.PutExtra("PlayerName", map.GetString("PlayerName"));
LocalBroadcastManager.GetInstance(this).SendBroadcast(intent);
break;
}
}
}
Instead of sending the data via separate strings I want to send my Match data as database file (if necessary as .ToString). Is it possible to achieve this and how can I thereafter retrieve the data.
Second of all I have my MatchStats as a list (IEnumerable or ObservableCollection). Is it possible to send this as a list or do I have to send each MatchStat seperately. By sending the Matchstats seperately my other device will not receive them in the desired order and not all MatchStats are received.
Instead of sending database data as database file I now solved this by sending the Matchstats in one file instead of sending all seperate data.
public async static void SendMatchStats(ObservableCollection<MatchStat> matchstats, Match match, int matchstatsize, string path)
{
if (!client.IsConnected)
client.Connect();
await Task.Delay(80);
try
{
var request = PutDataMapRequest.Create(path);
var map = request.DataMap;
MatchHelper mh = new MatchHelper();
int cnt = 1;
if (matchstatsize != 0)
{
map.PutString("Device", device);
map.PutString("Item", "MatchStats");
map.PutString("Home", match.Home);
map.PutString("Date", match.MatchDate.Date.ToString());
map.PutString("Time", match.MatchTime.ToString());
map.PutString("MatchStatSize", matchstatsize.ToString());
map.PutString("Path", path);
foreach (MatchStat matchstat in matchstats)
{
map.PutString("ActionItem" + cnt.ToString(), matchstat.ActionItem);
map.PutString("ActionMin" + cnt.ToString(), matchstat.ActionMin.ToString());
map.PutString("Color" + cnt.ToString(), matchstat.Color);
//map.PutString("ColorSchemeId", matchstat.ColorSchemeId.ToString());
map.PutString("GuestScore" + cnt.ToString(), matchstat.GuestScore.ToString());
map.PutString("HomeScore" + cnt.ToString(), matchstat.HomeScore.ToString());
if (matchstat.PlayerName == null)
map.PutString("PlayerName" + cnt.ToString(), "");
else
map.PutString("PlayerName" + cnt.ToString(), matchstat.PlayerName.ToString());
cnt++;
}
map.PutLong("UpdatedAt", DateTime.UtcNow.Ticks);
await WearableClass.DataApi.PutDataItem(client, request.AsPutDataRequest());
}
request.SetUrgent();
request.UnregisterFromRuntime();
}
catch
{ }
finally
{
client.Disconnect();
}
}
In my WearService I have my OnDataChanged:
case "MatchStats":
{
int size = int.Parse(map.GetString("MatchStatSize"));
intent.PutExtra("Home", map.GetString("Home"));
intent.PutExtra("Date", map.GetString("Date"));
intent.PutExtra("Time", map.GetString("Time"));
intent.PutExtra("MatchStatSize", map.GetString("MatchStatSize"));
intent.PutExtra("Path", map.GetString("Path"));
for (int cnt = 1; cnt <= size; cnt++)
{
intent.PutExtra("ActionItem" + cnt.ToString(), map.GetString("ActionItem" + cnt.ToString()));
intent.PutExtra("ActionMin" + cnt.ToString(), map.GetString("ActionMin" + cnt.ToString()));
intent.PutExtra("Color" + cnt.ToString(), map.GetString("Color" + cnt.ToString()));
intent.PutExtra("GuestScore" + cnt.ToString(), map.GetString("GuestScore" + cnt.ToString()));
intent.PutExtra("HomeScore" + cnt.ToString(), map.GetString("HomeScore" + cnt.ToString()));
intent.PutExtra("PlayerName" + cnt.ToString(), map.GetString("PlayerName" + cnt.ToString()));
Console.WriteLine("PutExtra " + map.GetString("ActionMin" + cnt.ToString()) + " min " + map.GetString("HomeScore" + cnt.ToString()) + "-" + map.GetString("GuestScore" + cnt.ToString()));
Console.WriteLine("GetStringExtra " + intent.GetStringExtra("ActionMin" + cnt.ToString()) + " min " + intent.GetStringExtra("HomeScore" + cnt.ToString()) + "-" + intent.GetStringExtra("GuestScore" + cnt.ToString()));
}
LocalBroadcastManager.GetInstance(this).SendBroadcast(intent);
break;
}
And in MainActivity I am processing the data in a seperate void InsertMatchstats:
private void InsertMatchStats(Intent intent)
{
MatchHelper mh = new MatchHelper();
Match match = mh.GetSpecificMatch(intent.GetStringExtra("Home"), DateTime.Parse(intent.GetStringExtra("Date")), TimeSpan.Parse(intent.GetStringExtra("Time")));
int size = int.Parse(intent.GetStringExtra("MatchStatSize"));
if (match != null)
{
for (int cnt = 1; cnt <= size; cnt++)
{
MatchStat matchstat = new MatchStat
{
MatchId = match.Id,
ActionItem = intent.GetStringExtra("ActionItem" + cnt.ToString()),
ActionMin = int.Parse(intent.GetStringExtra("ActionMin" + cnt.ToString())),
Color = intent.GetStringExtra("Color" + cnt.ToString()),
//ColorSchemeId = int.Parse(intent.GetStringExtra("ColorSchemeId"));
GuestScore = int.Parse(intent.GetStringExtra("GuestScore" + cnt.ToString())),
HomeScore = int.Parse(intent.GetStringExtra("HomeScore" + cnt.ToString())),
PlayerName = intent.GetStringExtra("PlayerName" + cnt.ToString()),
Sync = true
};
if (matchstat.Color == null)
matchstat.Color = "#FFFFFF";
MatchStat checkMatchStat = mh.CheckMatchStat(matchstat.HomeScore, matchstat.GuestScore, matchstat.ActionItem, matchstat.MatchId);
if (checkMatchStat == null)
mh.InsertMatchStat(matchstat);
else
{
checkMatchStat.ActionMin = matchstat.ActionMin;
checkMatchStat.Color = matchstat.Color;
//checkMatchStat.ColorSchemeId = matchstat.ColorSchemeId;
checkMatchStat.PlayerName = matchstat.PlayerName;
mh.UpdateMatchStat(checkMatchStat);
}
Console.WriteLine("PutExtra " + intent.GetStringExtra("ActionMin" + cnt.ToString()) + " min " + intent.GetStringExtra("HomeScore" + cnt.ToString()) + "-" + intent.GetStringExtra("GuestScore" + cnt.ToString()));
}
SendBack(intent.GetStringExtra("Path"));
}
}
Using this method the syncing is much faster and more precise. No data is lost and all data is received and processed in the right order.
As seen below, I have:
A class (Viatura) that creates a Vehicle.
Another class (ArrayViatura) that creates an array of Vehicles and subsequent methods.
In the form, I have to let the user define the size of this array of vehicles (numericupdown1), before doing any other operations within the form.
How do I make this value become the array size?
Thanks in Advance!
Here's the Code:
Class Viatura
`namespace IP_GonçaloDias_G00
{
class Viatura
{
string cvMatrícula;
string cvMarca;
string cvModelo;
string cvAnoFabrico;
string cvTipoPropulsão;
string cvCilindrada;
string cvPotência;
double cvAceleração;
string cvConsumoMédio;
string cvCor;
int cvTipoVeículo;
string cvCaixa;
DateTime cvPrimeiraMatrícula;
int cvNúmeroRegistos;
double cvKMPercorridos;
string cvDescriçãoVeículo;
double cvPreçoAquisição;
double cvPreçoProposto;
double cvPreçoVenda;
DateTime cvDataVenda;
string cvNomeCliente;
public Viatura(string matricula, string marca, string modelo, string anofabrico, string tipopropulsao, string cilindrada, string potencia, double aceleracao, string consumomedio, string cor, int tipoveiculo, string caixa, DateTime primeiramatricula, int numeroregistos, double km, string descricaoveiculo, double precoaquisicao, double precoproposto, double precovenda, DateTime datavenda, string nomecliente)
{
string cvMatrícula=matricula;
string cvMarca=marca;
string cvModelo=modelo;
string cvAnoFabrico=anofabrico;
string cvTipoPropulsão=tipopropulsao;
string cvCilindrada=cilindrada;
string cvPotência=potencia;
double cvAceleração=aceleracao;
string cvConsumoMédio=consumomedio;
string cvCor=cor;
int cvTipoVeículo=tipoveiculo;
string cvCaixa=caixa;
DateTime cvPrimeiraMatrícula=primeiramatricula;
int cvNúmeroRegistos=numeroregistos;
double cvKMPercorridos=km;
string cvDescriçãoVeículo=descricaoveiculo;
double cvPreçoAquisição=precoaquisicao;
double cvPreçoProposto=precoproposto;
double cvPreçoVenda=precovenda;
DateTime cvDataVenda=datavenda;
string cvNomeCliente =nomecliente;
}
public string CVMatrícula
{
get { return cvMatrícula; }
set { cvMatrícula = value; }
}
public string CVMarca
{
get { return cvMarca; }
set { cvMarca = value; }
}
public string CVModelo
{
get { return cvModelo; }
set { cvModelo = value; }
}
public string CVAnoFabrico
{
get { return cvAnoFabrico; }
set { cvAnoFabrico = value; }
}
public string CVTipoPropulsão
{
get { return cvTipoPropulsão; }
set { cvTipoPropulsão = value; }
}
public string CVCilindrada
{
get { return cvCilindrada; }
set { cvCilindrada = value; }
}
public string CVPotência
{
get { return cvPotência; }
set { cvPotência = value; }
}
public double CvAceleração
{
get { return cvAceleração; }
set { cvAceleração = value; }
}
public string CVConsumoMédio
{
get { return cvConsumoMédio; }
set { cvConsumoMédio = value; }
}
public string CVCor
{
get { return cvCor; }
set { cvCor = value; }
}
public int CVTipoVeículo
{
get { return cvTipoVeículo; }
set { cvTipoVeículo = value; }
}
public string CVCaixa
{
get { return cvCaixa; }
set { cvCaixa = value; }
}
public DateTime CVPrimeiraMatrícula
{
get { return cvPrimeiraMatrícula; }
set { cvPrimeiraMatrícula = value; }
}
public int CVNúmeroRegistos
{
get { return cvNúmeroRegistos; }
set { cvNúmeroRegistos = value; }
}
public double CVKMPercorridos
{
get { return cvKMPercorridos; }
set { cvKMPercorridos = value; }
}
public string CVDescriçãoVeículo
{
get { return cvDescriçãoVeículo; }
set { cvDescriçãoVeículo = value; }
}
public double CVPreçoAquisição
{
get { return cvPreçoAquisição; }
set { cvPreçoAquisição = value; }
}
public double CVPreçoProposto
{
get { return cvPreçoProposto; }
set { cvPreçoProposto = value; }
}
public double CVPreçoVenda
{
get { return cvPreçoVenda; }
set { cvPreçoVenda = value; }
}
public DateTime CVDataVenda
{
get { return cvDataVenda; }
set { cvDataVenda = value; }
}
public string CVNomeCliente
{
get { return cvNomeCliente; }
set { cvNomeCliente = value; }
}
}
}`
The Class ArrayViatura
`namespace IP_GonçaloDias_G00
{
class ArrayViaturas
{
public Viatura[] viaturas;
private int numElementos;
private int pointer;
public ArrayViaturas(int nElem)
{
viaturas = new Viatura[nElem];
numElementos = 0;
pointer = 0;
}
public int NumElementos
{
set { numElementos = value; }
get { return numElementos; }
}
public int Pointer
{
set { pointer = value; }
get { return pointer; }
}
public void InserirViatura(string matricula, string marca, string modelo, string anofabrico, string tipopropulsao, string cilindrada, string potencia, double aceleracao, string consumomedio, string cor, int tipoveiculo, string caixa, DateTime primeiramatricula, int numeroregistos, double km, string descricaoveiculo, double precoaquisicao, double precoproposto, double precovenda, DateTime datavenda, string nomecliente)
{
viaturas[numElementos] = new Viatura(matricula, marca, modelo, anofabrico, tipopropulsao, cilindrada, potencia, aceleracao, consumomedio, cor, tipoveiculo, caixa, primeiramatricula, numeroregistos, km, descricaoveiculo, precoaquisicao, precoproposto, precovenda, datavenda, nomecliente);
numElementos++;
}
public string MostrarViatura(int index, string sep)
{
string str = viaturas[index].CVMatrícula + sep + viaturas[index].CVMarca + sep + viaturas[index].CVModelo + sep + viaturas[index].CVAnoFabrico +
sep + viaturas[index].CVTipoPropulsão + sep + viaturas[index].CVCilindrada + sep + viaturas[index].CVPotência +
sep + viaturas[index].CvAceleração.ToString("f2") + "KMh" + sep + viaturas[index].CVConsumoMédio + sep + viaturas[index].CVCor
+ sep + viaturas[index].CVTipoVeículo.ToString("f2") + sep + viaturas[index].CVCaixa + sep + viaturas[index].CVPrimeiraMatrícula.ToShortDateString()
+ sep + viaturas[index].CVNúmeroRegistos.ToString("f2") + sep + viaturas[index].CVKMPercorridos.ToString("f2") + sep + viaturas[index].CVDescriçãoVeículo +
sep + viaturas[index].CVPreçoAquisição.ToString("f2") + sep + viaturas[index].CVPreçoProposto.ToString("f2") + sep + viaturas[index].CVPreçoVenda.ToString("f2") +
sep + viaturas[index].CVNomeCliente;
return str;
}
public void EliminarViatura(int index)
{
for (int i = index; i < NumElementos - 1; i++)
{
viaturas[i] = viaturas[i + 1];
}
NumElementos--;
if (pointer == NumElementos)
pointer--;
}
}
}`
The Form Code
`namespace IP_GonçaloDias_G00
{
public partial class RegistoViaturas : Form
{
string cvMatrícula="";
string cvMarca = "";
string cvModelo = "";
string cvAnoFabrico = "";
string cvTipoPropulsão = "";
string cvCilindrada = "";
string cvPotência = "";
double cvAceleração = 0;
string cvConsumoMédio = "";
string cvCor = "";
int cvTipoVeículo = 0;
string cvCaixa = "";
DateTime cvPrimeiraMatrícula=DateTime.Now;
int cvNúmeroRegistos = 0;
double cvKMPercorridos = 0;
string cvDescriçãoVeículo = "";
double cvPreçoAquisição = 0;
double cvPreçoProposto = 0;
double cvPreçoVenda = 0;
DateTime cvDataVenda = DateTime.Now;
string cvNomeCliente = "";
public RegistoViaturas()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
this.Close();
}
private void button7_Click(object sender, EventArgs e)
{
int size= Convert.ToInt32(numericUpDown1.Value);
ArrayViaturas viaturas = new ArrayViaturas(size);
MessageBox.Show("O tamanho definido para o Array é: " + viaturas.viaturas.Length);
groupBox2.Enabled = true;
}
}
}`
Assuming that the size is defined in TextBox1:
int size = 20;
int.TryParse(TextBox1.Text, out size);
public ArrayColab colaborators = new ArrayColab(size);
But note that its not a good idea to get the array size directly from user but you can define the array size yourself after detemening the user's need.
If the size is defined in NumericUpDown then:
public ArrayColab colaborators = new ArrayColab(NumericUpDown1.Value);
There is a method to read data from file
public static void ReadData(out StudentMarks[] Students, out int amount)
{
amount = 0;
Students = new StudentMarks[Max];
using (StreamReader reader = new StreamReader("C:\\Users\\Andrius\\Desktop\\Mokslams\\C#\\Pratybos\\P3\\P3.2\\StudentsMarks.csv"))
{
reader.ReadLine(); reader.ReadLine();
string line = null;
int[] marks;
marks = new int[Max];
while (null != (line = reader.ReadLine()))
{
string[] values = line.Split(',');
string surname = values[0];
string name = values[1];
string group = values[2];
int amountOfMarks = int.Parse(values[3]);
int i = 0; int yMax = 3 + amountOfMarks;int yMin = 4;
while (amountOfMarks >= i)
{
if (yMin <= yMax)
{
marks[i] = int.Parse(values[yMin]);
yMin++;
}
i++;
}
StudentMarks MarksObj = new StudentMarks(surname, name, group, amountOfMarks, marks);
Students[amount++] = MarksObj;
}
}
}
There is a class:
class StudentMarks
{
public const int Max = 50;
public string Surname { get; set; }
public string Name { get; set; }
public string Group { get; set; }
public int AmountOfMarks { get; set; }
public int[] Marks { get; set; }
public StudentMarks(string surname, string name, string group, int amountOfMarks, int[] marks)
{
Surname = surname;
Name = name;
Group = group;
AmountOfMarks = amountOfMarks;
Marks = marks;
}
}
The thing is, I cannot read "Marks", because I dont know how to initialize array in Class. My method should be working fine, I just can't put marks[i] into Students[i].Marks[y]
I don't understand why you want this.
but do you want like it?
class StudentMarks
{
public const int Max = 50;
public string Surname { get; set; }
public string Name { get; set; }
public string Group { get; set; }
public int[] Marks { get; private set; }
public StudentMarks(string surname, string name, string group, int amountOfMarks)
{
Surname = surname;
Name = name;
Group = group;
Marks = new int[amountOfMarks];
}
}
public static void ReadData(out StudentMarks[] Students, out int amount)
{
amount = 0;
Students = new StudentMarks[Max];
using (StreamReader reader = new StreamReader("C:\\Users\\Andrius\\Desktop\\Mokslams\\C#\\Pratybos\\P3\\P3.2\\StudentsMarks.csv"))
{
reader.ReadLine(); reader.ReadLine();
string line = null;
while (null != (line = reader.ReadLine()))
{
string[] values = line.Split(',');
string surname = values[0];
string name = values[1];
string group = values[2];
int i = 0; int yMax = 3 + amountOfMarks;int yMin = 4;
Students[amount] = new StudentMarks(surname, name, group, amountOfMark);
while (amountOfMarks >= i)
{
if (yMin <= yMax)
{
Students[amount].Marks[i] = int.Parse(values[yMin]);
yMin++;
}
i++;
}
amount++;
}
}
}
I've searched StackOverflow for an answer to this, but can't find a clear answer.
I've this Player Class (Yes i've posted the class before)
namespace Tennis_Match
{
class Player
{
private string first_name;
private string middle_name;
private string last_name;
private DateTime dob;
private string nat;
private char gender;
public string First_name { get { return first_name; } set { first_name = value; } }
public string Middle_name { get {return middle_name; } set { middle_name = value; } }
public string Last_name { get { return last_name; } set { last_name = value; } }
public DateTime Dob { get { return dob; } set { dob = value; } }
public string Nat { get { return nat; } set { nat = value; } }
public char Gender { get { return gender; } set { gender = value; } }
public Player(string first_name, string last_name, string middle_name, DateTime dob, string nat, char gender)
{
this.first_name = first_name;
this.last_name = last_name;
this.middle_name = middle_name;
this.dob = dob;
this.nat = nat;
this.gender = gender;
}
public override string ToString()
{
return first_name + " " + middle_name + " " + last_name + " " + dob + " "+ nat + " " + gender;
}
public static int CalculateAge(DateTime dob)
{
int years = DateTime.Now.Year - dob.Year;
if ((dob.Month > DateTime.Now.Month) || (dob.Month == DateTime.Now.Month && dob.Day > DateTime.Now.Day))
years--;
return years;
}
private List<string> content = new List<string>();
public string FileName { get; set; }
public string Delimiter { get; set; }
private void Load()
{
TextFieldParser par = new TextFieldParser(FileName);
par.TextFieldType = FieldType.Delimited;
par.SetDelimiters(Delimiter);
while (!par.EndOfData)
{
string[] fields = par.ReadFields();
foreach (string field in fields)
{
Console.WriteLine(field);
}
}
par.Close();
}
public void RunReadCSVFile(string fn, string delim = "|")
{
FileName = fn;
Delimiter = delim;
Load();
}
public string GetLine(string fileName, int line)
{
using (var sr = new StreamReader(fileName))
{
for (int i = 1; i < line; i++)
sr.ReadLine();
return sr.ReadLine();
}
}
}
}
Then I've another class tournament. I want to sort a textfile by among other Last_name. I've got an idea that i might need to use IComparable to sort the file.
The file is structured like this:
1|Mariuss|Luka|Thygesen|1986-07-25|NAURU|NR
First you have nothing to sort. So add to class
static List<Player> players = new List<Player>();
Next you need to add items to List in following function
private void Load()
{
TextFieldParser par = new TextFieldParser(FileName);
par.TextFieldType = FieldType.Delimited;
par.SetDelimiters(Delimiter);
while (!par.EndOfData)
{
string[] fields = par.ReadFields();
foreach (string field in fields)
{
Console.WriteLine(field);
}
//-----------------------------Add -----------------------
Player newPlayer = new Player(fields[0], fields[1], fields[2], DateTime.Parse(fields[3]), fields[4], fields[5][0]);
players.Add(newPlayer);
}
par.Close();
}
Now you have something to sort. So add a sort method (or CompareTo())
public void Sort()
{
players = players.OrderBy(x => new { x.last_name, x.first_name, x.middle_name }).ToList();
}
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.