Java Reference
In-Depth Information
if (score >= 90.0 )
System.out.print( "A" );
else
if (score >= 80.0 )
System.out.print( "B" );
else
if (score >= 70.0 )
System.out.print( "C" );
else
if (score >= 60.0 )
System.out.print( "D" );
else
System.out.print( "F" );
if (score >= 90.0 )
System.out.print( "A" );
else if (score >= 80.0 )
System.out.print( "B" );
else if (score >= 70.0 )
System.out.print( "C" );
else if (score >= 60.0 )
System.out.print( "D" );
else
System.out.print( "F" );
Equivalent
This is better
(a)
(b)
F IGURE 3.3
A preferred format for multiple alternatives is shown in (b) using a multi-way
if-else statement.
The execution of this if statement proceeds as shown in FigureĀ 3.4. The first condition
(score >= 90.0) is tested. If it is true , the grade is A . If it is false , the second condition
(score >= 80.0) is tested. If the second condition is true , the grade is B . If that condition
is false , the third condition and the rest of the conditions (if necessary) are tested until a
condition is met or all of the conditions prove to be false . If all of the conditions are false ,
the grade is F . Note that a condition is tested only when all of the conditions that come before
it are false .
false
score >= 90
false
true
score >= 80
grade is A
false
true
score >= 70
grade is B
false
true
score >= 60
grade is C
true
grade is D
grade is F
F IGURE 3.4
You can use a multi-way if-else statement to assign a grade.
 
Search WWH ::




Custom Search