Section 8.8. GradeBook Case Study: Using an Array to Store Grades


8.8. GradeBook Case Study: Using an Array to Store Grades

This section further evolves class GradeBook, introduced in Chapter 4 and expanded in Chapters 56. Recall that this class represents a grade book used by a professor to store and analyze a set of student grades. Previous versions of the class process a set of grades entered by the user, but do not maintain the individual grade values in instance variables of the class. Thus, repeat calculations require the user to reenter the same grades. One way to solve this problem would be to store each grade entered in an instance of the class. For example, we could create instance variables grade1, grade2,..., grade10 in class GradeBook to store 10 student grades. However, the code to total the grades and determine the class average would be cumbersome, and the class would not be able to process any more than 10 grades at a time. In this section, we solve the problem by storing the grades in an array.

Storing Student Grades in an Array in Class GradeBook

The version of class GradeBook (Fig. 8.13) presented here uses an array of Integers to store the grades of several students on a single exam. This eliminates the need to repeatedly input the same set of grades. Array grades is declared as an instance variable in line 5 therefore, each GradeBook object maintains its own set of grades. The class's constructor (lines 811) has two parametersthe name of the course and an array of grades. When an application (e.g., class GradeBookTest in Fig. 8.14) creates a GradeBook object, the application passes an existing Integer array to the constructor, which assigns the array's reference to instance variable grades (line 10). The size of the array grades is determined by the class that passes the array to the constructor. Thus, a GradeBook object can process a variable number of grades. The grade values in the passed array could have been input from a user or read from a file on disk (as discussed in Chapter 18). In our test application, we simply initialize an array with a set of grade values (Fig. 8.14, lines 67). Once the grades are stored in instance variable grades of class GradeBook, all the class's methods can access the elements of grades as needed to perform various calculations.

Figure 8.13. GradeBook class using an array to store test grades.

  1  ' Fig. 8.13: GradeBook.vb  2  ' GradeBook class uses an array to store test grades.  3  Public Class GradeBook  4     Private courseNameValue As String ' name of course  5     Private grades As Integer() ' array of student grades  6  7     ' two-argument constructor initializes courseNameValue and grades  8     Public Sub New(ByVal name As String, ByVal gradesArray As Integer())  9        CourseName = name ' initializes courseNameValue via property 10        grades = gradesArray ' store reference to gradesArray 11     End Sub ' New 12 13     ' property CourseName 14     Public Property CourseName() As String 15        Get 16           Return courseNameValue 17        End Get 18 19        Set(ByVal name As String) 20           courseNameValue = name 21        End Set 22     End Property ' Course Name 23 24     ' display a welcome message to the GradeBook user 25     Public Sub DisplayMessage() 26        Console.WriteLine("Welcome to the grade book for " & vbCrLf & _ 27           CourseName & vbCrLf) 28     End Sub ' DisplayMessage 29 30     ' perform various operations on the data 31     Public Sub ProcessGrades() 32        OutputGrades() ' output grades array 33 34        ' call method GetAverage to calculate the average grade 35        Console.WriteLine("Class average is {0:F2}", GetAverage()) 36 37        ' call methods GetMinimum and GetMaximum 38        Console.WriteLine("Lowest grade is {0}", GetMinimum()) 39        Console.WriteLine("Highest grade is {0}", GetMaximum()) 40 41        ' call OutputBarChart to print grade distribution chart 42        OutputBarChart() 43     End Sub ' ProcessGrades 44 45     ' find minimum grade 46     Public Function GetMinimum() As Integer 47        Dim lowGrade As Integer = grades(0) ' assume grades(0) is smallest 48 49        ' loop through grades array                              50        For Each grade As Integer In grades                      51           ' if grade lower than lowGrade, assign it to lowGrade 52           If grade < lowGrade Then                           53              lowGrade = grade ' new lowest grade                54           End If                                                55        Next                                                     56 57        Return lowGrade ' return lowest grade 58     End Function ' GetMinimum 59 60     ' find maximum grade 61     Public Function GetMaximum() As Integer 62        Dim highGrade As Integer = grades(0) ' assume grades(0) is largest 63 64        ' loop through grades array 65        For Each grade As Integer In grades 66           ' if grade greater than highGrade, assign it to highGrade 67           If grade > highGrade Then 68              highGrade = grade ' new highest grade 69           End If 70        Next 71 72        Return highGrade ' return highest grade 73     End Function ' GetMaximum 74 75     ' determine average grade for test 76     Public Function GetAverage() As Double 77        Dim total As Integer = 0 ' initialize total 78 79        ' sum grades for one student        80        For Each grade As Integer In grades 81           total += grade                   82        Next                                83 84        ' return average of grades 85        Return (total / grades.Length) 86     End Function ' GetAverage 87 88     ' output bar chart displaying grade distribution 89     Public Sub OutputBarChart() 90        Console.WriteLine(vbCrLf & "Grade distribution:") 91 92        ' stores frequency of grades in each range of 10 grades 93        Dim frequency As Integer() = New Integer(10) {} 94 95        ' for each grade, increment the appropriate frequency 96        For Each grade As Integer In grades                   97           frequency(grade \ 10) += 1                         98        Next                                                  99 100       ' for each grade frequency, print bar in chart 101       For count As Integer = 0 To frequency.GetUpperBound(0) 102          ' output bar label ("00-09: ", ..., "90-99: ", "100: " ) 103          If count = 10 Then 104             Console.Write("{0, 5:D}: ", 100) 105          Else 106             Console.Write("{0, 2:D2}-{1, 2:D2}: ", _ 107                count * 10, count * 10 + 9) 108          End If 109 110          ' print bar of asterisks 111          For stars As Integer = 0 To frequency(count) - 1 112             Console.Write("*") 113          Next 114 115          Console.WriteLine() ' start a new line of output 116       Next 117    End Sub ' OutputBarChart 118 119    ' output the contents of the grades array 120    Public Sub OutputGrades() 121       Console.WriteLine("The grades are:" & vbCrLf) 122 123       ' output each student's grade                         124       For student As Integer = 0 To grades.GetUpperBound(0) 125          Console.WriteLine("Student {0, 2:D}: {1, 3:D}", _  126             student + 1, grades(student))                   127       Next                                                  128 129        Console.WriteLine() 130     End Sub ' OutputGrades 131  End Class ' GradeBook 

Figure 8.14. GradeBookTest creates a GradeBook object using an array of grades, then invokes method ProcessGrades to analyze them.

  1  ' Fig. 8.14: GradeBookTest.vb  2  ' Create       GradeBook object using any array of grades.  3  Module GradeBookTest  4     Sub Main()  5        ' array of student grades                     6        Dim gradesArray As Integer() = _              7           {87, 68, 94, 100, 83, 78, 85, 91, 76, 87}  8        Dim gradeBooks As New GradeBook( _  9           "CS101 Introduction to Visual Basic Programming", gradesArray) 10        gradeBooks.DisplayMessage() 11        gradeBooks.ProcessGrades() 12     End Sub ' Main 13  End Module ' GradeBookTest 

 Welcome to the grade book for CS101 Introduction to Visual Basic Programming The grades are: Student  1:  87 Student  2:  68 Student  3:  94 Student  4: 100 Student  5:  83 Student  6:  78 Student  7:  85 Student  8:  91 Student  9:  76 Student 10:  87 Class average is 84.90 Lowest grade is 68 Highest grade is 100 Grade distribution: 00-09: 10-19: 20-29: 30-39: 40-49: 50-59: 60-69: * 70-79: ** 80-89: **** 90-99: **   100: * 



Method ProcessGrades (lines 3143) contains a series of method calls that result in the output of a report summarizing the grades. Line 32 calls method OutputGrades to print the contents of the array grades. Lines 124127 in method OutputGrades use a For statement to output each student's grade. Lines 125126 use counter variable student's value to output each grade next to a particular student number (see the output in Fig. 8.14). Although array indices start at 0, a professor would typically number students starting at 1. Thus, lines 125126 output student + 1 as the student number to produce grade labels "Student 1: ", "Student2: ", and so on.

Method ProcessGrades next calls method GetAverage (line 35) to obtain the average of the grades in the array. Method GetAverage (lines 7686) uses a For Each statement to total the values in array grades before calculating the average. The loop control variable declaration in the For Each's header (e.g., grade As Integer) indicates that for each iteration, the Integer variable grade takes on the next successive value in the array grades. The averaging calculation in line 85 uses grades.Length to determine the number of grades being averaged.

Lines 3839 in method ProcessGrades call methods GetMinimum and GetMaximum to determine the lowest and highest grades of any student on the exam, respectively. Each of these methods uses a For Each statement to loop through array grades. Lines 5055 in method GetMinimum loop through the array, and lines 5254 compare each grade to low-Grade. If a grade is less than lowGrade, lowGrade is set to that grade. When line 57 executes, lowGrade contains the lowest grade in the array. Method GetMaximum (lines 6173) works similarly to method GetMinimum.

Finally, line 42 in method ProcessGrades calls method OutputBarChart to print a distribution chart of the grade data using a technique similar to that in Fig. 8.6. Lines 9698 calculate the frequency of grades in each category. Line 106 passes to the method Console.Write the format string "{0, 2:D2}-{1, 2:D2}", which indicates that arguments 0 and 1 (the first two arguments after the format string) should take the format D2 (base 10 decimal number format using two digits) for display purposesthus, 8 would be converted to 08 and 10 would remain as 10. Recall that the number 2 before the colon indicates that the result should be output right justified in a field of width 2. The dash that separates the curly braces } and { is printed to display the range of the grades (see the output of Fig. 8.14).

Line 93 declares and creates array frequency of 11 Integers to store the frequency of grades in each grade category. For each grade in array grades, lines 9698 increment the appropriate element of the frequency array. To determine which element to increment, line 97 divides the current grade by 10 using integer division. For example, if grade is 85, line 97 increments frequency[ 8 ] to update the count of grades in the range 8089. Lines 101116 next print the bar chart (see the output of Fig. 8.14) based on the values in the frequency array. Like lines 1517 of Fig. 8.6, lines 111113 of Fig. 8.13 use a value in array frequency to determine the number of asterisks to display in each bar.

Class GradeBookTest That Demonstrates Class GradeBook

The application in Fig. 8.14 creates an object of class GradeBook (Fig. 8.13) using the Integer array gradesArray (declared and initialized in lines 67). Lines 89 pass a course name and gradesArray to the GradeBook constructor. Line 10 displays a welcome message, and line 11 invokes the GradeBook object's ProcessGrades method. The output presents an analysis of the 10 grades in gradeBooks.

Software Engineering Observation 8.1

A test harness (or test application) is responsible for creating an object of the class being tested and providing it with data. This data could come from any of several sources. Test data can be placed directly into an array with an array initializer, it can be entered by the user at the keyboard, it can be read from a file (as you will see in Chapter 18), or it can arrive over a network (as you will see in Chapter 23). After passing this data to the class's constructor to instantiate the object, the test harness should call the object's methods to verify that they work properly.




Visual BasicR 2005 for Programmers. DeitelR Developer Series
Visual Basic 2005 for Programmers (2nd Edition)
ISBN: 013225140X
EAN: 2147483647
Year: 2004
Pages: 435

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net