Java Reference
In-Depth Information
If student's grade is greater than or equal to 60
Print “Passed”
Else
Print “Failed”
prints “Passed” if the student's grade is greater than or equal to 60, but prints “Failed” if
it's less than 60. In either case, after printing occurs, the next pseudocode statement in se-
quence is “performed.”
The preceding
If
…
Else
pseudocode statement can be written in Java as
if
(grade >=
60
)
System.out.println(
"Passed"
);
else
System.out.println(
"Failed"
);
The body of the
else
is also indented. Whatever indentation convention you choose
should be applied consistently throughout your programs.
Good Programming Practice 4.1
Indent both body statements of an
if
…
else
statement. Many IDEs do this for you.
Good Programming Practice 4.2
If there are several levels of indentation, each level should be indented the same additional
amount of space.
UML Activity Diagram for an
if
…
else
Statement
Figure 4.3 illustrates the flow of control in the
if
…
else
statement. Once again, the sym-
bols in the UML activity diagram (besides the initial state, transition arrows and final
state) represent action states and decisions.
[grade < 60]
[grade >= 60]
print “Failed”
print “Passed”
Fig. 4.3
|
if
…
else
double-selection statement UML activity diagram.
Nested
if
…
else
Statements
A program can test multiple cases by placing
if
…
else
statements inside other
if
…
else
statements to create
nested
if
…
else
statements
. For example, the following pseudo-
code represents a nested
if
…
else
that prints
A
for exam grades greater than or equal to
90,
B
for grades 80 to 89,
C
for grades 70 to 79,
D
for grades 60 to 69 and
F
for all other
grades: