Both types
of if statements we’ve seen so far allow us to specify up to two
alternatives depending on the truth
value of the condition (if true do A, otherwise do B). There are times, however, that we’d like to
select among multiple alternatives depending on the value of a variable. For example, suppose we’d like to write a
program that displays a message of “how it feels outside” based on the user
input of the outside temperature. The
alternatives are listed in this table: Temperature is How it feels less than 32 Frigid 32-50
Cold 51-70 Cool 71-90 Warm greater than 90 Hot The logic of
selecting among the different alternatives would go as follows: first check
if the temperature is less than 32. If
it is, print out “Frigid” and we’re done.
If it’s not, then check if it’s in the 32-50 range. An important thing to observe is that as
soon as one of the conditions is satisfied, no other condition need
to be checked further. This sort of
logic can be expressed using compound if-else statements that take on the following form: if (condition1) block 1 else if (condition 2) block 2 else if (condition 3) block 3 . . . else // default case: if
no prior condition applies block n Notice that
each of the else keywords, except for the last one, is immediately followed
by an if block.
The following schematic shows how the flow of execution proceeds
through the various else-if blocks.
Back to our
example. The full program goes as: import java.util.Scanner; public class HowItFeels { public static void main(String[] args) { Scanner s = new Scanner(System.in); System.out.print("Tell me the
temperature and I'll tell you how
it feels: "); int temp = s.nextInt(); if (temp < 32) System.out.println("Frigid."); // No need to check that temp is >=
32. It's implied // since the previous condition must be
false in order // for this one to be evaluated. else if (temp <= 50) System.out.println("Cold."); else if (temp <= 70) System.out.println("Cool."); else if (temp <= 90) System.out.println("Warm."); else System.out.println("Hot."); } } |
||
|
|