Search code examples
c#.netvisual-studiostreamreader

StreamReader only displaying last item in selected file


I am very new to this and cannot figure out what I am doing wrong.

It only processes and displays one line of results, but I need it to process and display everything in the file. The files that can be selected are .txt files, those have multiple students names along with 3 test scores for the program to calculate and display an average and a letter grade, which it does perfectly, but only for one student for each file, when the files have probably 10 names in each.

The code in question is:

//VARIABLES
string gLetter = null, studentName = null;
int test1 = 0, test2 = 0, test3 = 0, avg = 0;

private void processButton_Click(object sender, EventArgs e)
{
    try
    {
        getdata();
        calculatedata();
        displaydata();
        resetitems();
    }
    catch
    {
        MessageBox.Show("Error");
    }
}

private void getdata()
{
    try
    {

        StreamReader inputFile;
       
        if (openFile.ShowDialog() == DialogResult.OK)
        {
            inputFile = File.OpenText(openFile.FileName);
            while (!inputFile.EndOfStream)
            {
                studentName = inputFile.ReadLine();
                test1 = int.Parse(inputFile.ReadLine());
                test2 = int.Parse(inputFile.ReadLine());
                test3 = int.Parse(inputFile.ReadLine());
            }
        }
    }
    catch (Exception)
    {

        MessageBox.Show("Error");
    }
}

private void calculatedata()
{
    try
    {
        //calc avg
        avg = (test1 + test2 + test3) / 3;
        
        //find gLetter
        if (avg >= 90)
            gLetter = "A";
        else if (avg >= 80)
            gLetter = "B";
        else if (avg >= 70)
            gLetter = "C";
        else if (avg >= 60)
            gLetter = "D";
        else if (avg < 60)
            gLetter = "F";
    }
    catch
    {
        MessageBox.Show("Error");
    }
}

private void displaydata()
{
    try
    {
        listBox1.Items.Add(studentName + "\t" + avg.ToString("N2") + "\t" + gLetter);
    }
    catch (Exception)
    {
        MessageBox.Show("Error");
    }
}

private void resetitems()
{
    openFile.FileName = " ";
}

private void exitButton_Click(object sender, EventArgs e)
{
    try
    {
        Application.Exit();
    }
    catch
    {
        MessageBox.Show("Error");
    }
}

Solution

  • Your problem is that on method getData() you are reading allí lines to EOF, but you must add It to a lista or call t'he Other methods inside of the method because you are overriding the variables allí time and you only get the last line