Student
Class: Nested if
…else
StatementsThe example of Figs. 5.5–5.6 demonstrates a nested if
…else
statement that determines a student’s letter grade based on the student’s average in a course.
Student
Class Student
(Fig. 5.5) stores a student’s name and average and provides properties for manipulating these values. The class contains:
Auto-implemented string
property Name
(line 7) to store a Student
’s name.
Instance variable average
of type int
(line 8) to store a Student
’s average in a course and a corresponding Average
property (lines 18–36) to get and set the Student
’s average
. Average
’s set
accessor uses nested if
statements (lines 28–34) to validate the value that’s assigned to the Average
property. These statements ensure that the value is greater than 0
and less than or equal to 100
; otherwise, instance variable average
’s value is left unchanged. Each if
statement contains a simple condition—i.e., one that makes only a single test. In Section 6.11, you’ll see how to use logical operators to write compound conditions that conveniently combine several simple conditions. If the condition in line 28 is true
, only then will the condition in line 30 be tested, and only if the conditions in both lines 28 and 30 are true
will the statement in line 32 execute.
A constructor (lines 11–15) that sets the Name
and Average
properties.
Read-only property LetterGrade
(lines 39–68), which uses nested if
…else
statements to determine the Student
’s letter grade based on the Student
’s average
. A read-only property provides only a get
accessor. Note that the local variable letterGrade
is initialized to string.Empty
(line 43), which represents the empty string (that is, a string
containing no characters).
StudentTest
To demonstrate the nested if
statements and nested if
…else
statements in class Student
’s Average
and LetterGrade
properties, respectively, method Main
(Fig. 5.6) creates two Student
objects (lines 9–10). Next, lines 12–15 display each Student
’s name, average and letter grade by accessing the objects’ Name
, Average
and LetterGrade
properties, respectively.