Exercise Solutions: Classes Part 2

Line numbers are for reference. They may not match your code exactly.

GetGradeLevel Method

This method returns the student’s level based on the number of credits they have earned.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
   public string GetGradeLevel(int credits)
   {
      if (credits <= 29)
      {
         return "freshman";
      }
      else if (credits <= 59)
      {
         return "sophomore";
      }
      else if (credits <= 89)
      {
         return "junior";
      }
      else
      {
         return "senior";
      }
   }

Back to the Exercises

AddGrade Method

This method accepts two parameters—a number of course credits and a numerical grade (0.0-4.0).

1
2
3
4
5
6
7
8
   public void AddGrade(int courseCredits, double grade)
   {
      // Update the appropriate properties: NumberOfCredits, Gpa
      double totalQualityScore = Gpa * NumberOfCredits;
      totalQualityScore += courseCredits * grade;
      NumberOfCredits += courseCredits;
      Gpa = totalQualityScore / NumberOfCredits;
   }

Back to the Exercises

ToString & Equals

Add custom Equals() and ToString() methods to the Student class.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
   public override string ToString()
   {
      return Name + " (Credits: " + NumberOfCredits + ", GPA: " + Gpa + ")";
   }

   public override bool Equals(object obj)
   {
      if (obj == this)
      {
         return true;
      }

      if (obj == null)
      {
         return false;
      }

      if (obj.GetType() != GetType())
      {
         return false;
      }

      Student studentObj = obj as Student;
      return StudentId == studentObj.StudentId;
   }

Back to the Exercises