I’m trying to count the times any names occur in a txt file. Basically output one line for each name in the file and on each line print the number of occurrences followed by the name into a list box.
So far my code looks like this-
private void openFileToolStripMenuItem_Click(object sender, EventArgs e)
{
//open text file
string name;
string unique;
string line;
int count = 0;
StreamReader reader;
//Set the filter for the dialog control
openFileDialog1.Filter = FILTER;
//check to see if the user has selected a file to open
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
//open the selected file
reader = File.OpenText(openFileDialog1.FileName);
//process the file
//repeat while it's not the end of the loop
while (!reader.EndOfStream)
{
//read the names in the file
name = reader.ReadLine();
unique = reader.ReadLine();
//display item in the listbox
listBox1.Items.Add(name.PadRight(20) + CalcUniqueNames(unique));
//add the data to the list
nameLIst.Add(name);
//count the unique names
count++;
}
//close the file
reader.Close();
}
}
//CalcUniqueNames(unique) is a method which is supposed to count the names.
private int CalcUniqueNames(string name)
{
int count = 0;
for (int i = 0; i < uniqueList.Count; i++)
{
if (uniqueList[i] == "Alex")
{
count++ ;
}
else if (uniqueList[i] == "Garian")
{
count++;
}
else if (uniqueList[i] == "Daniel")
{
count++;
}
else if (uniqueList[i] == "Jarrod")
{
count++;
}
else if (uniqueList[i] == "Rachel")
{
count++;
}
else if (uniqueList[i] == "Sean")
{
count++;
}
}
return count;
}
I don’t know why but when I run the programme the names and the number is displays, but the number always states 0. Any help would be appreciated. I thought may be I could go
count + 1
but an error pops up.
I’m new to coding, only have a few months experience.
Micaiah Brown is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.