Search code examples
c#loopsparametersassignment-operatorref

Looping ref parameters


I'm finishing up a homework assignment and I'm having a small issue with looping through the function to return parameters for each name in the file. I'm hoping someone can quickly look at this and advise on where I should place a loop. I've tried it everywhere that makes sense to me. Quick synopsis of how the function works. It will look at a file with multiple students, grades, & hours for the class then calculate the GPA for each student. Return the student name and GPA to Main which will then call another function to create the output files. Currently the only file being created is for the final student in the file (Miguel Ortiz & his GPA).

Sorry this code is so ugly. The sample file is ridiculous!

The input file looks like this:

Jack Johnson
A
2
C
3
F
2
D
2
B
4
A
4
Miguel Ortiz
C
4
A
3
F
2

Code written:

public static void ProcessGrades(ref string File, out string Name, out double GPA)
  {
    string FilePath = @"C:\Users\heathi\Documents\Visual Studio 2013\Projects\" +
      @"GPA Calculation\GPA Calculation\bin\Release\";
        StreamReader inFile = new StreamReader(FilePath + File);
    double gpa = 0.0;
    string letterGrade = "";
    string line;
    double grade = 0;
    double hours = 0;
    double points = 0;
    double i = 0;
    bool result = false;
    string studentName = "";

    while ((line = inFile.ReadLine()) != null)
    {
      if (line.Length > 1)
      {
        if (studentName != line)
        {
          if (hours != 0)
          {
            gpa = (points / hours);
            gpa = Math.Round(gpa, 2);
            Console.WriteLine(studentName + " GPA " + gpa.ToString());
          }
          studentName = line;
          points = 0;
          hours = 0;
          grade = 0;
        }
      }
      else
      {
        result = double.TryParse(line, out i);
        if (result == true)
        {
          hours += double.Parse(line);
          points += (grade * double.Parse(line));
        }
        else
        {
          letterGrade = line;

          switch (letterGrade)
          {
            case "A":
              grade = 4;
              break;
            case "B":
              grade = 3;
              break;
            case "C":
              grade = 2;
              break;
            case "D":
              grade = 1;
              break;
           case "F":
              grade = 0;
              break;
          }
        }
      }
    }
    gpa = (points / hours);
    gpa = Math.Round(gpa, 2);
    Console.WriteLine(studentName + " GPA " + gpa.ToString());

    Name = studentName;
    GPA = gpa;
  } // end ProcessGrades

Solution

  • Instead of returning a name, I think you need to create a Dictionary and in the loop, put each student and grade in the Dictionary.

    Return the dictionary from the function for further processing.