t u t o r i a l 2009 pearson education, inc. all rights reserved. 1 18 student grades application...
DESCRIPTION
2009 Pearson Education, Inc. All rights reserved. 3 In this tutorial you will learn: ■Understand the similarities and differences between one-dimensional and two-dimensional arrays. ■Declare and manipulate two-dimensional arrays. ■Understand how to use two-dimensional arrays. ■Use nested For...Next loops. ■Use RadioButton s to enable users to select exactly one option out of several. ObjectivesTRANSCRIPT
T U T O R I A L
2009 Pearson Education, Inc. All rights reserved.
1
18Student Grades
ApplicationIntroducing Two-DimensionalArrays and RadioButtons
2009 Pearson Education, Inc. All rights reserved.
2
Outline
18.1 Test-Driving the Student Grades Application
18.2 Two-Dimensional Rectangular Arrays18.3 Using RadioButtons18.4 Inserting Code into the Student Grades
Application
2009 Pearson Education, Inc. All rights reserved.
3
In this tutorial you will learn: ■ Understand the similarities and differences
between one-dimensional and two-dimensional arrays.
■ Declare and manipulate two-dimensional arrays.■ Understand how to use two-dimensional arrays.■ Use nested For...Next loops.■ Use RadioButtons to enable users to select
exactly one option out of several.
Objectives
Application Requirements
2009 Pearson Education, Inc. All rights reserved.
4
18.1 Test-Driving the Student Grades Application
A teacher issues three tests to a class of 10 students. The grades on these tests are integers in the range from 0 to 100. The teacher has asked you to develop an application to keep track of each student’s average and the class average. The teacher has also asked that there be a choice to view the grades as either number or letter grades.The application should allow a user to input the student’s three test grades, then compute each student’s average and the class average.
2009 Pearson Education, Inc. All rights reserved.
5
Test-Driving the Student Grades Application
■ Run the completed application (Fig. 18.1).
Figure 18.1 | Running the completed Student Grades application.
2009 Pearson Education, Inc. All rights reserved.
6
Test-Driving the Student Grades Application (Cont.)
Figure 18.2 | Inputting data to the Student Grades application.
■ Enter numbers in the Test 1:, Test 2: andTest 3: TextBoxes (Fig. 18.2).
2009 Pearson Education, Inc. All rights reserved.
7
Test-Driving the Student Grades Application (Cont.)
■ Click the Submit Grades Button to calculate the student’s average (Fig. 18.3).
Figure 18.3 | Displaying the student’s numerical grade.
Numeric RadioButtonselected by default
2009 Pearson Education, Inc. All rights reserved.
8
Test-Driving the Student Grades Application (Cont.)
■ Once 10 students have been entered, all the controls in the Input Grades GroupBox are disabled (Fig. 18.4).
Figure 18.4 | Input Grades GroupBox disabled after 10 students.
Input Grades GroupBox disabledListBox withnumeric gradesdisplayed
Label with numeric class average displayed
2009 Pearson Education, Inc. All rights reserved.
9
Test-Driving the Student Grades Application (Cont.)
■ Change the ListBox’s data to letter grades (Fig. 18.5).
Figure 18.5 | Displaying the students’ letter grades.
Select the Letter RadioButton
ListBox with letter grades displayed
Label with letter class average displayed
2009 Pearson Education, Inc. All rights reserved.
10
■ Two-dimensional arrays require two indices to identify particular elements, in the form array(i, j).
– Rectangular arrays are often used to represent tables of values arranged in rows and columns.
■ Figure 18.6 illustrates a two-dimensional rectangular array.
18.2 Two-Dimensional Rectangular Arrays
Figure 18.6 | Two-dimensional rectangular array with three rows and four columns.
2009 Pearson Education, Inc. All rights reserved.
11
■ Two-dimensional arrays are initialized much like one-dimensional arrays:Dim numbers As Integer(,) = New Integer(0 To 1, 0 To 1) {}numbers(0, 0) = 1numbers(0, 1) = 2numbers(1, 0) = 3numbers(1, 1) = 4
■ Note that a comma (,) is required inside the parentheses following the data type to indicate that the array is two-dimensional.
■ You can also write the declaration as:Dim numbers(0 To 1, 0 To 1) As Integer
18.2 Two-Dimensional Rectangular Arrays (Cont.)
2009 Pearson Education, Inc. All rights reserved.
12
■ Two-dimensional arrays also may be initialized using an initializer list:
Dim numbers As Integer(,) = New Integer(,) {{1, 2}, {3, 4}}
■ The preceding declaration can also be written asDim numbers As Integer(,) = {{1, 2}, {3, 4}}
■ You can specify the lower bounds of an array implicitly:
Dim numbers As Integer(,) = New Integer(1, 1) {}Dim numbers(1, 1) As Integer
18.2 Two-Dimensional Rectangular Arrays (Cont.)
2009 Pearson Education, Inc. All rights reserved.
13
■ A RadioButton is a small white circle that either is blank or contains a smaller dot.
– When a RadioButton is selected, a dot appears in the circle.
– RadioButtons represent a set of mutually exclusive options—only one can be selected at a time.
– By default, all RadioButtons added directly to a Form or GroupBox become part of the same group.
■ If the RadioButton is checked, the Checked property returns the Boolean value True.
18.3 Using RadioButtons
2009 Pearson Education, Inc. All rights reserved.
14
When the user clicks the Submit Grades Button:Retrieve the student’s grades from the TextBoxesAdd the student’s test scores to the arrayDisplay the student’s test scores and average in the ListBoxDisplay the class’s average in the Class average: LabelClear the student’s test scores from the TextBoxes
If 10 students have been entered Disable the input controls
When the user selects the Numeric RadioButton:Display each student’s numeric test scores and average in the
ListBoxDisplay the class’s numeric average in the Class average:
Label
When the user selects the Letter RadioButton:Display each student’s letter test scores and average in the
ListBoxDisplay the class’s letter average in the Class average: Label
18.3 Using RadioButtons (Cont.)
2009 Pearson Education, Inc. All rights reserved.
15
Action Control Event
Label the application’s components inputGroupBox, viewGroupBox, test1Label, test2Label, test3Label, classAverageLabel
Application is run
submitButton
Retrieve the student’s grades from the TextBoxes
test1TextBox, test2TextBox, test3TextBox
Add the student’s test scores to the array
Display the student’s test scores and average in the ListBox
gradesListBox
Display the class’s average in the Class average: Label
averageLabel
Click
Figure 18.7 | ACE table for the Student Grades application. (Part 1 of 2.)
■ Use an ACE table to convert the pseudocode into Visual Basic (Figure 18.7).
Action/Control/Event (ACE) Table for the Student Grades Application
2009 Pearson Education, Inc. All rights reserved.
16
Action Control Event
Clear the student’s test scores from the TextBoxes
test1TextBox, test2TextBox, test3TextBox
I f 10 students have been entered
Click
Disable the input controls inputGroupBox
numericRadioButton CheckChanged
Display each student’s numeric test scores and average in the ListBox
gradesListBox
Display the class’s numeric average in the Class average: Label
averageLabel
letterRadioButton CheckChanged
Display each student’s letter test scores average in the ListBox
gradesListBox
Display the class’s letter average in the Class average: Label
averageLabel
Figure 18.7 | ACE table for the Student Grades application. (Part 2 of 2.)
Action/Control/Event (ACE) Table for the Student Grades Application (Cont.)
2009 Pearson Education, Inc. All rights reserved.
17
■ Select the View GroupBox on the template application’s Form, and add two RadioButtons.
■ Name the left one numericRadioButton, and set its Text property to Numeric. Name the right one letterRadioButton, and set its Text property to Letter.
■ Set the Checked property of numericRadioButton to True (Fig. 18.8).
Adding RadioButtons to the View GroupBox
Figure 18.8 | RadioButtons placed in the GroupBox.
2009 Pearson Education, Inc. All rights reserved.
18
GUI Design TipUse RadioButtons when the user must choose only one option from a group.
2009 Pearson Education, Inc. All rights reserved.
19
GUI Design TipAlways place each group of RadioButtons in a separate container (such as a GroupBox).
2009 Pearson Education, Inc. All rights reserved.
20
GUI Design TipAlign groups of RadioButtons either horizontally or vertically.
2009 Pearson Education, Inc. All rights reserved.
21
Good Programming Practice
Append the RadioButton suffix to RadioButton control names.
2009 Pearson Education, Inc. All rights reserved.
22
Error-Prevention Tip
To avoid subtle logic errors, one RadioButton in a group is often selected by default, by setting its Checked property to True. This can be done using code or by setting the value using the Properties window.
2009 Pearson Education, Inc. All rights reserved.
23
Declaring a Two-Dimensional Array
■ Line 2 (Fig. 18.9) declares a 10-by-3 array of Integers to contain the test scores.
■ Each row in the array represents a student. Each column represents a test.
Figure 18.9 | Declaring a two-dimensional array.
2009 Pearson Education, Inc. All rights reserved.
24Finishing the Submit Grades Button’sClick Event Handler
■ Double click the Submit Grades Button to display its Click event handler (Fig. 18.10).
Figure 18.10 | Storing the student’s test scores.
Store the student’s testscores in the array
2009 Pearson Education, Inc. All rights reserved.
25
■ The For...Next statement (Fig. 18.11) reviews each of the student’s test scores.
■ Retrieve the highest index of the array’s second dimension, indicated by passing 1 as the argument to GetUpperBound.
Finishing the Submit Grades Button’sClick Event Handler (Cont.)
2009 Pearson Education, Inc. All rights reserved.
26Finishing the Submit Grades Button’sClick Event Handler (Cont.)
Figure 18.11 | Displaying the output.
Iterating over the student’s test scores
Determining how todisplay the test scores
Calling the LetterGrade method
Displaying the student’s average
Update the number of students
Displaying the class average
2009 Pearson Education, Inc. All rights reserved.
27
■ If grades array is full, line 51 (Fig. 18.12) disablesthe Input Grades GroupBox.
– Disabling a GroupBox disables all the controls it contains.■ The Length property of a two-dimensional array would
return the total number of elements (rows times columns).
Finishing the Submit Grades Button’sClick Event Handler (Cont.)
Figure 18.12 | Application does not allow more than 10 data entries.
Disable the input controls when the grades array is full
2009 Pearson Education, Inc. All rights reserved.
28
■ The For...Next statement (Fig. 18.13) sums the grades contained in the specified student row of the grades array.
■ The format control string "{0:F}" formats the test average with exactly two digits following the decimal point.
Coding Methods to Average Test Grades
2009 Pearson Education, Inc. All rights reserved.
29
Figure 18.13 | Calculating a student’s test average.
Calculate thestudent’s test average
Coding Methods to Average Test Grades (Cont.)
Sum the student’s test grades
2009 Pearson Education, Inc. All rights reserved.
30
■ The CalculateStudentAverage method (Fig. 18.14) uses nested For...Next statements to iterate over the columns in each row.
Figure 18.14 | Calculating the class’s test average.
Coding Methods to Average Test Grades (Cont.)
Outer For...Next statement
iterates over each row
Inner For...Next statement iterates over each column
Calculate the class’s test average
2009 Pearson Education, Inc. All rights reserved.
31
■ Double click the Numeric RadioButton to generate its CheckedChanged event handler (Fig. 18.15).
Figure 18.15 | Method numericRadioButton_CheckedChanged.
Coding Event Handlers for the RadioButtons
Displaying the class’s grades
2009 Pearson Education, Inc. All rights reserved.
32
■ Double click the Letter RadioButton to generate its event handler (Fig. 18.16).
Figure 18.16 | Method letterRadioButton_CheckedChanged.
Coding Event Handlers for theRadioButtons (Cont.)
Displaying the class’s grades
2009 Pearson Education, Inc. All rights reserved.
33
■ Method DisplayClassGrades (Fig. 18.17) displays each student’s grades and test average, as well as the class average, in the format selected by the user.
Coding Event Handlers for theRadioButtons (Cont.)
2009 Pearson Education, Inc. All rights reserved.
34
Figure 18.17 | Method DisplayClassGrades.
Coding Event Handlers for theRadioButtons (Cont.)
Displaying the class’s average
Inner For...Next statement adds the grades in each column of the
current row to the output String
Outer For...Next statementiterates over each row of the array
2009 Pearson Education, Inc. All rights reserved.
35
1 Public Class StudentGradesForm 2 Dim grades As Integer(,) = New Integer(0 To 9, 0 To 2) {} 3 Dim studentCount As Integer = 0 ' number of students entered 4 5 ' handles submit button click event 6 Private Sub submitButton_Click(ByVal sender As System.Object, _ 7 ByVal e As System.EventArgs) Handles submitButton.Click 8 9 ' retrieve the student's grades 10 grades(studentCount, 0) = Convert.ToInt32(test1TextBox.Text) 11 grades(studentCount, 1) = Convert.ToInt32(test2TextBox.Text) 12 grades(studentCount, 2) = Convert.ToInt32(test3TextBox.Text) 13 14 ' output string containing the student's grades and average 15 Dim output As String = _ 16 "Student " & studentCount & ControlChars.Tab
■ Figure 18.18 presents the source code for the Student Grades application.
Outline
(1 of 11 )
Creating a two-dimensional array
Assigning values to elements of a two-dimensional array
2009 Pearson Education, Inc. All rights reserved.
36
17 18 ' add each test grade to the output 19 For column As Integer = 0 To grades.GetUpperBound(1) 20 ' if the Letter RadioButton is checked 21 If letterRadioButton.Checked = True Then 22 ' add letter grade to the output 23 output &= ControlChars.Tab & _ 24 LetterGrade(grades(studentCount, column)) 25 Else 26 ' add number grade to the output 27 output &= ControlChars.Tab & _ 28 grades(studentCount, column) 29 End If 30 Next 31 Next 32 ' add the student's test average to the output 33 output &= ControlChars.Tab & _ 34 CalculateStudentAverage(studentCount)
Outline
(2 of 11 )
Using the Checked property of a RadioButton control
Calling the LetterGrade method with an element of a two-dimensional array
Accessing an element of a two-dimensional array
Iterating over the columns in a row of a two-dimensional array
2009 Pearson Education, Inc. All rights reserved.
37
35 36 gradesListBox.Items.Add(output) ' add output to the ListBox 37 38 studentCount += 1 ' update number of students entered 39 40 ' display the class average 41 averageLabel.Text = CalculateClassAverage() 42 43 ' clear the input TextBoxes and set focus to first TextBox 44 test1TextBox.Clear() 45 test2TextBox.Clear() 46 test3TextBox.Clear() 47 test1TextBox.Focus() 48 49 ' limit number of students 50 If studentCount = grades.GetUpperBound(0) + 1 Then 51 inputGroupBox.Enabled = False ' disable GroupBox's controls 52 End If 53 End Sub ' submitButton_Click
Outline
(3 of 11 )
Determining the number of rows in a two-dimensional array
Disabling all the controls in a GroupBox
2009 Pearson Education, Inc. All rights reserved.
38
54 55 ' calculates a student's test average 56 Function CalculateStudentAverage(ByVal row As Integer) As String 57 Dim gradeTotal As Integer = 0 ' student's total grade 58 59 ' sum the grades for the student 60 For column As Integer = 0 To grades.GetUpperBound(1) 61 gradeTotal += grades(row, column) 62 Next 63 64 Dim studentAverage As String = "" ' output string 65 66 ' calculate the student's test average 67 If letterRadioButton.Checked = True Then 68 studentAverage = _ 69 LetterGrade(gradeTotal / (grades.GetUpperBound(1) + 1)) 70 Else 71 studentAverage = String.Format("{0:F}", _ 72 (gradeTotal / (grades.GetUpperBound(1) + 1))) 73 End If
Outline
(4 of 11 )
Iterating over the columns in a row of a two-dimensional array
Using the Checked property of a RadioButton control
Calculating the student’s average and formatting it as a number with two digits after the decimal point
2009 Pearson Education, Inc. All rights reserved.
39
74 75 Return studentAverage ' return the student's average 76 End Function ' CalculateStudentAverage 77 78 ' calculates the class average 79 Function CalculateClassAverage() As String 80 Dim classTotal As Integer = 0 ' class's total grade 81 82 ' loop through all rows 83 For row As Integer = 0 To studentCount - 1 84 ' loop through all columns 85 For column As Integer = 0 To grades.GetUpperBound(1) 86 classTotal += grades(row, column) ' add grade to total 87 Next column 88 Next row 89 90 Dim classAverage As String = "" ' output string 91
Outline
(5 of 11 )
Using nested For... Next statements to iterate over the columns in each row of a two-dimensional array
2009 Pearson Education, Inc. All rights reserved.
40
92 ' if the Letter RadioButton is checked, return letter grade 93 If letterRadioButton.Checked = True Then 94 classAverage = LetterGrade(classTotal / _ 95 (studentCount * (grades.GetUpperBound(1) + 1))) 96 Else ' return number grade 97 classAverage = String.Format("{0:F}", (classTotal / _ 98 (studentCount * (grades.GetUpperBound(1) + 1)))) 99 End If 100 101 Return classAverage ' return the class average 102 End Function ' CalculateClassAverage 103 104 ' determines a letter grade corresponding to a numeric grade 105 Function LetterGrade(ByVal grade As Double) As String 106 Dim output As String ' the letter grade to return 107
Outline
(6 of 11 )
Using the Checked property of a RadioButton control
Calculating the class’s average and formatting it as a number with two digits after the decimal point
2009 Pearson Education, Inc. All rights reserved.
41
108 ' determine the correct letter grade 109 Select Case grade 110 Case Is >= 90 111 output = "A" 112 Case Is >= 80 113 output = "B" 114 Case Is >= 70 115 output = "C" 116 Case Is >= 60 117 output = "D" 118 Case Else 119 output = "F" 120 End Select 121 122 Return output ' return the letter grade 123 End Function ' LetterGrade 124
Outline
(7 of 11 )
2009 Pearson Education, Inc. All rights reserved.
42
125 ' handles Numeric RadioButton's CheckChanged event 126 Private Sub numericRadioButton_CheckedChanged(ByVal sender As _ 127 System.Object, ByVal e As System.EventArgs) _ 128 Handles numericRadioButton.CheckedChanged 129 130 ' if the Numeric RadioButton is checked, display number grades 131 If numericRadioButton.Checked = True AndAlso _ 132 studentCount > 0 Then 133 134 DisplayClassGrades() 135 End If 136 End Sub ' numericRadioButton_CheckedChanged 137 138 ' handles Letter RadioButton's CheckChanged event 139 Private Sub letterRadioButton_CheckedChanged(ByVal sender As _ 140 System.Object, ByVal e As System.EventArgs) _ 141 Handles letterRadioButton.CheckedChanged 142
Outline
(8 of 11 )
Handling the CheckedChanged event of a RadioButton control
Handling the CheckedChanged event of a RadioButton control
2009 Pearson Education, Inc. All rights reserved.
43
143 ' if the Letter RadioButton is checked, display letter grades 144 If letterRadioButton.Checked = True AndAlso _ 145 studentCount > 0 Then 146 147 DisplayClassGrades() 148 End If 149 End Sub ' letterRadioButton_CheckedChanged 150 151 ' display the grades for all students entered 152 Sub DisplayClassGrades() 153 gradesListBox.Items.Clear() ' clear the ListBox 154 155 ' add the header to the ListBox 156 gradesListBox.Items.Add(ControlChars.Tab & ControlChars.Tab _ 157 & "Test 1" & ControlChars.Tab _ 158 & "Test 2" & ControlChars.Tab _ 159 & "Test 3" & ControlChars.Tab & "Average") 160
Outline
(9 of 11 )
2009 Pearson Education, Inc. All rights reserved.
44
161 ' loop through all the rows 162 For row As Integer = 0 To studentCount - 1 163 Dim output As String = "Student " & row & ControlChars.Tab 164 165 ' loop through all the columns 166 For column As Integer = 0 To grades.GetUpperBound(1) 167 If letterRadioButton.Checked = True Then 168 ' add letter grade to output string 169 output &= ControlChars.Tab & _ 170 LetterGrade(grades(row, column)) 171 Else 172 ' add number grade to output string 173 output &= ControlChars.Tab & (grades(row, column)) 174 End If 175 Next column 176
Outline
(10 of 11 )
Outer For...Next statement iterates over the rows of a two-dimensional array
Inner For...Next statement iterates over the columns of a row in a two-dimensional array
Using the control variable’s name to improve readability of nested For...Next statements
2009 Pearson Education, Inc. All rights reserved.
45
177 ' add the student's average to the output 178 output &= ControlChars.Tab & CalculateStudentAverage(row) 179 180 ' add the output to the ListBox 181 gradesListBox.Items.Add(output) 182 Next row 183 184 ' update the class average 185 averageLabel.Text = CalculateClassAverage() 186 End Sub ' DisplayClassGrades 187 End Class ' StudentGradesForm
Outline
(11 of 11 )
Using the control variable’s name to improve readability of nested For...Next statements