next up previous
Next: Ambiguity of the else Up: Unit 05 Previous: Nested if's

Nested if's with mutually excluding conditions

A common use of nested if's is when the conditions in the nested if's are mutually excluding, i.e., no two of them can be simultaneously true.

Example: Based on the value of the temperature (an integer) print a message according to the following table:

temperature t message
30 < t hot
20 < t < = 30 warm
10 < t < = 20 fine
t < = 10 cold

int temp;
...
if (30 < temp)
  System.out.println("hot");
else if (20 < temp)
  System.out.println("warm");
else if (10 < temp)
  System.out.println("fine");
else
  System.out.println("cold");

Observations:


next up previous
Next: Ambiguity of the else Up: Unit 05 Previous: Nested if's