T U T O R I A L Student Grades Application Introducing Two-Dimensional Arrays and RadioButtons 2009 Pearson Education, Inc.
Download ReportTranscript T U T O R I A L Student Grades Application Introducing Two-Dimensional Arrays and RadioButtons 2009 Pearson Education, Inc.
1
T U T O R I A L
18
Student Grades
Application
Introducing Two-Dimensional
Arrays and RadioButtons
2009 Pearson Education, Inc. All rights reserved.
2
Outline
18.1 Test-Driving the Student Grades
Application
18.2 Two-Dimensional Rectangular Arrays
18.3 Using RadioButtons
18.4 Inserting Code into the Student Grades
Application
2009 Pearson Education, Inc. All rights reserved.
3
Objectives
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.
2009 Pearson Education, Inc. All rights reserved.
4
18.1 Test-Driving the Student Grades Application
Application Requirements
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.)
■ Enter numbers in the Test 1:, Test 2: and
Test 3: TextBoxes (Fig. 18.2).
Figure 18.2 | Inputting data to the Student Grades application.
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).
Numeric RadioButton
selected by default
Figure 18.3 | Displaying the student’s numerical grade.
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).
ListBox with
numeric grades
displayed
Input Grades GroupBox disabled
Label with numeric
class average
displayed
Figure 18.4 | Input Grades GroupBox disabled after 10 students.
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).
ListBox with letter
grades displayed
Label with letter
class average
displayed
Select the Letter RadioButton
Figure 18.5 | Displaying the students’ letter grades.
2009 Pearson Education, Inc. All rights reserved.
10
18.2 Two-Dimensional Rectangular Arrays
■ 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.
Figure 18.6 | Two-dimensional rectangular array with three rows and four columns.
2009 Pearson Education, Inc. All rights reserved.
11
18.2 Two-Dimensional Rectangular Arrays (Cont.)
■ Two-dimensional arrays are initialized much like onedimensional arrays:
Dim numbers As Integer(,) = New Integer(0 To 1, 0 To 1) {}
numbers(0, 0) = 1
numbers(0, 1) = 2
numbers(1, 0) = 3
numbers(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
2009 Pearson Education, Inc. All rights reserved.
12
18.2 Two-Dimensional Rectangular Arrays (Cont.)
■ 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 as
Dim 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
2009 Pearson Education, Inc. All rights reserved.
13
18.3 Using RadioButtons
■ 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.
2009 Pearson Education, Inc. All rights reserved.
14
18.3 Using RadioButtons (Cont.)
When the user clicks the Submit Grades Button:
Retrieve the student’s grades from the TextBoxes
Add the student’s test scores to the array
Display the student’s test scores and average in the ListBox
Display the class’s average in the Class average: Label
Clear 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 ListBox
Display 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 ListBox
Display the class’s letter average in the Class average: Label
2009 Pearson Education, Inc. All rights reserved.
Action/Control/Event (ACE) Table for the
Student Grades Application
15
■ Use an ACE table to convert the pseudocode into
Visual Basic (Figure 18.7).
Action
Control
Event
Label the application’s components
inputGroupBox,
viewGroupBox,
test1Label,
test2Label,
test3Label,
classAverageLabel
Application is run
submitButton
Click
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
Figure 18.7 | ACE table for the Student Grades application. (Part 1 of 2.)
2009 Pearson Education, Inc. All rights reserved.
Action/Control/Event (ACE) Table for the
Student Grades Application (Cont.)
Action
Control
Event
Clear the student’s test scores from the
TextBoxes
test1TextBox,
test2TextBox,
test3TextBox
Click
16
If 10 students have been entered
Disable the input controls
inputGroupBox
numericRadioButton
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
Display each student’s letter test scores
average in the ListBox
gradesListBox
Display the class’s letter average in the
Class average: Label
averageLabel
CheckChanged
CheckChanged
Figure 18.7 | ACE table for the Student Grades application. (Part 2 of 2.)
2009 Pearson Education, Inc. All rights reserved.
17
Adding RadioButtons to the View GroupBox
■ 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).
Figure 18.8 | RadioButtons placed in the GroupBox.
2009 Pearson Education, Inc. All rights reserved.
18
GUI Design Tip
Use RadioButtons when the user must choose only
one option from a group.
2009 Pearson Education, Inc. All rights reserved.
19
GUI Design Tip
Always place each group of RadioButtons in a
separate container (such as a GroupBox).
2009 Pearson Education, Inc. All rights reserved.
20
GUI Design Tip
Align 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.
Finishing the Submit Grades Button’s
Click Event Handler
24
■ Double click the Submit Grades Button to display
its Click event handler (Fig. 18.10).
Store the student’s test
scores in the array
Figure 18.10 | Storing the student’s test scores.
2009 Pearson Education, Inc. All rights reserved.
Finishing the Submit Grades Button’s
Click Event Handler (Cont.)
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.
2009 Pearson Education, Inc. All rights reserved.
Finishing the Submit Grades Button’s
Click Event Handler (Cont.)
26
Iterating over the student’s
test scores
Determining how to
display the test scores
Calling the LetterGrade method
Displaying the student’s average
Update the number of students
Displaying the class average
Figure 18.11 | Displaying the output.
2009 Pearson Education, Inc. All rights reserved.
Finishing the Submit Grades Button’s
Click Event Handler (Cont.)
27
■ If grades array is full, line 51 (Fig. 18.12) disables
the 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).
Disable the input controls when the
grades array is full
Figure 18.12 | Application does not allow more than 10 data entries.
2009 Pearson Education, Inc. All rights reserved.
28
Coding Methods to Average Test Grades
■ 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.
2009 Pearson Education, Inc. All rights reserved.
29
Coding Methods to Average Test Grades (Cont.)
Sum the student’s test grades
Calculate the
student’s test average
Figure 18.13 | Calculating a student’s test average.
2009 Pearson Education, Inc. All rights reserved.
30
Coding Methods to Average Test Grades (Cont.)
■ The CalculateStudentAverage method (Fig. 18.14)
uses nested For...Next statements to iterate over the
columns in each row.
Outer For...Next statement
iterates over each row
Inner For...Next statement
iterates over each column
Calculate the class’s test average
Figure 18.14 | Calculating the class’s test average.
2009 Pearson Education, Inc. All rights reserved.
31
Coding Event Handlers for the RadioButtons
■ Double click the Numeric RadioButton to generate its
CheckedChanged event handler (Fig. 18.15).
Displaying the class’s grades
Figure 18.15 | Method numericRadioButton_CheckedChanged.
2009 Pearson Education, Inc. All rights reserved.
Coding Event Handlers for the
RadioButtons (Cont.)
32
■ Double click the Letter RadioButton to generate
its event handler (Fig. 18.16).
Displaying the class’s grades
Figure 18.16 | Method letterRadioButton_CheckedChanged.
2009 Pearson Education, Inc. All rights reserved.
Coding Event Handlers for the
RadioButtons (Cont.)
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.
2009 Pearson Education, Inc. All rights reserved.
Coding Event Handlers for the
RadioButtons (Cont.)
34
Outer For...Next statement
iterates over each row of the array
Inner For...Next statement adds the
grades in each column of the current
row to the output String
Displaying the class’s average
Figure 18.17 | Method DisplayClassGrades.
2009 Pearson Education, Inc. All rights reserved.
35
Outline
■ Figure 18.18 presents the source code for the
Student Grades application.
(1 of 11 )
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Public Class StudentGradesForm
Dim grades As Integer(,) = New Integer(0 To 9, 0 To 2) {}
Dim studentCount As Integer = 0 ' number of students entered
Creating a twodimensional array
' handles submit button click event
Private Sub submitButton_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles submitButton.Click
' retrieve the student's grades
grades(studentCount, 0) = Convert.ToInt32(test1TextBox.Text)
grades(studentCount, 1) = Convert.ToInt32(test2TextBox.Text)
grades(studentCount, 2) = Convert.ToInt32(test3TextBox.Text)
Assigning values to
elements of a twodimensional array
' output string containing the student's grades and average
Dim output As String = _
"Student " & studentCount & ControlChars.Tab
2009 Pearson Education,
Inc. All rights reserved.
36
Outline
(2 of 11 )
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
' add each test grade to the output
For column As Integer = 0 To grades.GetUpperBound(1)
' if the Letter RadioButton is checked
If letterRadioButton.Checked = True Then
' add letter grade to the output
output &= ControlChars.Tab & _
LetterGrade(grades(studentCount, column))
Else
' add number grade to the output
output &= ControlChars.Tab & _
grades(studentCount, column)
Iterating over the columns in
a row of a two-dimensional
array
Using the Checked property
of a RadioButton control
Calling the LetterGrade
method with an element of a
two-dimensional array
End If
Next
Next
' add the student's test average to the output
output &= ControlChars.Tab & _
Accessing an element of a
two-dimensional array
CalculateStudentAverage(studentCount)
2009 Pearson Education,
Inc. All rights reserved.
37
Outline
(3 of 11 )
35
36
gradesListBox.Items.Add(output) ' add output to the ListBox
37
38
39
studentCount += 1 ' update number of students entered
40
41
42
' display the class average
averageLabel.Text = CalculateClassAverage()
43
44
45
' clear the input TextBoxes and set focus to first TextBox
test1TextBox.Clear()
test2TextBox.Clear()
46
47
48
49
test3TextBox.Clear()
test1TextBox.Focus()
50
If studentCount = grades.GetUpperBound(0) + 1 Then
inputGroupBox.Enabled = False ' disable GroupBox's controls
End If
51
52
53
Determining the
number of rows in a
two-dimensional
array
' limit number of students
Disabling all the
controls in a
GroupBox
End Sub ' submitButton_Click
2009 Pearson Education,
Inc. All rights reserved.
38
Outline
(4 of 11 )
54
55
56
57
' calculates a student's test average
Function CalculateStudentAverage(ByVal row As Integer) As String
Dim gradeTotal As Integer = 0 ' student's total grade
58
59
60
61
62
63
' sum the grades for the student
For column As Integer = 0 To grades.GetUpperBound(1)
gradeTotal += grades(row, column)
Next
64
65
66
Dim studentAverage As String = "" ' output string
' calculate the student's test average
67
68
If letterRadioButton.Checked = True Then
studentAverage = _
LetterGrade(gradeTotal / (grades.GetUpperBound(1) + 1))
69
70
71
72
73
Else
studentAverage = String.Format("{0:F}", _
(gradeTotal / (grades.GetUpperBound(1) + 1)))
End If
Iterating over the columns
in a row of a twodimensional 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
Outline
(5 of 11 )
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
Return studentAverage ' return the student's average
End Function ' CalculateStudentAverage
' calculates the class average
Function CalculateClassAverage() As String
Dim classTotal As Integer = 0 ' class's total grade
' loop through all rows
For row As Integer = 0 To studentCount - 1
' loop through all columns
For column As Integer = 0 To grades.GetUpperBound(1)
classTotal += grades(row, column) ' add grade to total
Next column
Next row
Using nested For...
Next statements to
iterate over the
columns in each row
of a two-dimensional
array
Dim classAverage As String = "" ' output string
91
2009 Pearson Education,
Inc. All rights reserved.
40
Outline
(6 of 11 )
92
93
' if the Letter RadioButton is checked, return letter grade
If letterRadioButton.Checked = True Then
94
95
96
97
98
99
100
101
102
103
classAverage = LetterGrade(classTotal / _
(studentCount * (grades.GetUpperBound(1) + 1)))
Else ' return number grade
classAverage = String.Format("{0:F}", (classTotal / _
(studentCount * (grades.GetUpperBound(1) + 1))))
End If
104
105
106
107
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
Return classAverage ' return the class average
End Function ' CalculateClassAverage
' determines a letter grade corresponding to a numeric grade
Function LetterGrade(ByVal grade As Double) As String
Dim output As String ' the letter grade to return
2009 Pearson Education,
Inc. All rights reserved.
41
Outline
(7 of 11 )
108
109
110
' determine the correct letter grade
Select Case grade
Case Is >= 90
111
output = "A"
112
113
Case Is >= 80
output = "B"
114
115
116
117
118
119
Case Is >= 70
output = "C"
Case Is >= 60
output = "D"
Case Else
output = "F"
120
121
122
123
124
End Select
Return output ' return the letter grade
End Function ' LetterGrade
2009 Pearson Education,
Inc. All rights reserved.
42
Outline
(8 of 11 )
125
126
' handles Numeric RadioButton's CheckChanged event
Private Sub numericRadioButton_CheckedChanged(ByVal sender As _
System.Object, ByVal e As System.EventArgs) _
Handles numericRadioButton.CheckedChanged
127
128
129
130
131
132
133
134
135
136
DisplayClassGrades()
End If
End Sub ' numericRadioButton_CheckedChanged
137
138
139
140
141
' handles Letter RadioButton's CheckChanged event
Private Sub letterRadioButton_CheckedChanged(ByVal sender As _
System.Object, ByVal e As System.EventArgs) _
Handles letterRadioButton.CheckedChanged
Handling the
CheckedChanged
event of a
RadioButton
control
' if the Numeric RadioButton is checked, display number grades
If numericRadioButton.Checked = True AndAlso _
studentCount > 0 Then
Handling the
CheckedChanged
event of a
RadioButton
control
142
2009 Pearson Education,
Inc. All rights reserved.
43
Outline
(9 of 11 )
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
' if the Letter RadioButton is checked, display letter grades
If letterRadioButton.Checked = True AndAlso _
studentCount > 0 Then
DisplayClassGrades()
End If
End Sub ' letterRadioButton_CheckedChanged
' display the grades for all students entered
Sub DisplayClassGrades()
gradesListBox.Items.Clear() ' clear the ListBox
' add the header to the ListBox
gradesListBox.Items.Add(ControlChars.Tab & ControlChars.Tab _
& "Test 1" & ControlChars.Tab _
& "Test 2" & ControlChars.Tab _
& "Test 3" & ControlChars.Tab & "Average")
160
2009 Pearson Education,
Inc. All rights reserved.
44
Outline
(10 of 11 )
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
' loop through all the rows
For row As Integer = 0 To studentCount - 1
Dim output As String = "Student " & row & ControlChars.Tab
' loop through all the columns
For column As Integer = 0 To grades.GetUpperBound(1)
If letterRadioButton.Checked = True Then
' add letter grade to output string
output &= ControlChars.Tab & _
LetterGrade(grades(row, column))
Else
' add number grade to output string
output &= ControlChars.Tab & (grades(row, column))
End If
Next column
Outer For...Next
statement iterates over
the rows of a twodimensional 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
Outline
(11 of 11 )
177
' add the student's average to the output
178
output &= ControlChars.Tab & CalculateStudentAverage(row)
179
180
181
' add the output to the ListBox
gradesListBox.Items.Add(output)
182
Next row
183
184
' update the class average
185
186
Using the control
variable’s name to
improve readability of
nested For...Next
statements
averageLabel.Text = CalculateClassAverage()
End Sub ' DisplayClassGrades
187 End Class ' StudentGradesForm
2009 Pearson Education,
Inc. All rights reserved.