Java Reference
In-Depth Information
prints the value of println 's conditional-expression argument. The conditional expres-
sion in this statement evaluates to the string "Passed" if the boolean expression student-
Grade >= 60 is true and to the string "Failed" if it's false. Thus, this statement with the
conditional operator performs essentially the same function as the if else statement
shown earlier in this section. The precedence of the conditional operator is low, so the en-
tire conditional expression is normally placed in parentheses. We'll see that conditional ex-
pressions can be used in some situations where if else statements cannot.
Error-Prevention Tip 4.2
Use expressions of the same type for the second and third operands of the ?: operator to
avoid subtle errors.
4.7 Student Class: Nested if else Statements
The example of Figs. 4.4-4.5 demonstrates a nested if else statement that determines
a student's letter grade based on the student's average in a course.
Class Student
Class Student (Fig. 4.4) has features similar to those of class Account (discussed in
Chapter 3). Class Student stores a student's name and average and provides methods for
manipulating these values. The class contains:
•i st e i le name of type String (line 5) to store a Student 's name
•i st e i le average of type double (line 6) to store a Student 's average in
a course
• a constructor (lines 9-18) that initializes the name and average —in Section 5.9,
you'll learn how to express lines 15-16 and 37-38 more concisely with logical
operators that can test multiple conditions
•m t s setName and getName (lines 21-30) to set and get the Student 's name
•m t s setAverage and getAverage (lines 33-46) to set and get the Student 's
average
•m t d getLetterGrade (lines 49-65), which uses nested if else statements to
determine the Student 's letter grade based on the Student 's average
The constructor and method setAverage each use nested if statements (lines 15-17
and 37-39) to validate the value used to set the average —these statements ensure that the
value is greater than 0.0 and less than or equal to 100.0 ; otherwise, average 's value is left
unchanged . Each if statement contains a simple condition. If the condition in line 15 is true ,
only then will the condition in line 16 be tested, and only if the conditions in both line 15
and line 16 are true will the statement in line 17 execute.
Software Engineering Observation 4.1
Recall from Chapter 3 that you should not call methods from constructors (we'll explain why
in Chapter 10, Object-Oriented Programming: Polymorphism and Interfaces). For this
reason, there is duplicated validation code in lines 15-17 and 37-39 of Fig. 4.4 and in
subsequent examples.
 
 
Search WWH ::




Custom Search