Calculate Average from a Textfile C#

余生颓废 提交于 2019-12-13 21:59:51

问题


private void button1_Click(object sender, EventArgs e)
{
    try
    {
        var WriteToFile = new System.IO.StreamWriter("student.txt"); //create textfile in default directory
        WriteToFile.Write(txtStudNum.Text + ", " + txtStudName.Text + ", " + txtModCode.Text + ", " + txtModMark.Text);
        WriteToFile.Close();
        this.Close(); 
    }

    catch (System.IO.DirectoryNotFoundException ex)
    {
        //add error message
    }
}

private void button3_Click(object sender, EventArgs e)
{
    File.AppendAllText("student.txt", "\r\n" + txtStudNum.Text + ", " +  
    txtStudName.Text + ", " + txtModCode.Text + ", " + txtModMark.Text);
}

private void button4_Click(object sender, EventArgs e)
{

}

I want to calculate the average for txtModMark from the textfile once all the values have been entered. It will go under button 4 so when I click it, it calculates. I need to know how to skip the first few columns per row and get to the last column to perform the average calculation.


回答1:


What's the point in reading from file then parse it and then convert to INT and then calculate average when you can do it directly using s List<int> like below:

declare a List<int> in your Form

List<int> marks = new List<int>();

Store the marks in button click event

  private void button1_Click(object sender, EventArgs e)
    {
        try
        {
            var WriteToFile = new System.IO.StreamWriter("student.txt"); //create textfile in default directory
            WriteToFile.Write(txtStudNum.Text + ", " + txtStudName.Text + ", " + txtModCode.Text + ", " + txtModMark.Text);
            WriteToFile.Close();
           marks.Add(Convert.ToInt32(txtModMark.Text)); //add to list
        }

        catch (System.IO.DirectoryNotFoundException ex)
        {
            //add error message
        }
    }

In button4 click event calculate the average

private void button4_Click(object sender, EventArgs e)
{
   int totalmarks = 0;
   foreach(int m in marks)
    totalmarks += m;

  MessageBox.Show("Average Is: " + totalmarks / marks.Count);
}


来源:https://stackoverflow.com/questions/32166227/calculate-average-from-a-textfile-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!